Web Fundamentals: Flexbox and Grid Layout

Site Admin · 11 Sep 2026 · 5 views

Flexbox Lays Out One Dimension

Flexbox is a layout mode for arranging items in a single row or column. You set display flex on a container, and its direct children become flexible items. The container controls alignment along the main axis and the cross axis.

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

justify-content distributes items along the main axis; space-between pushes the first item to the start and the last to the end. align-items positions items along the cross axis, and center keeps them vertically centered regardless of height differences.

<nav class="toolbar">
  <a href="/">Home</a>
  <a href="/blog">Blog</a>
  <a href="/about">About</a>
</nav>

The flex container can also wrap onto multiple lines and control spacing between wrapped rows with gap. Flexbox is best when you are distributing items in one direction, like a toolbar or a card row.

Grid Lays Out Two Dimensions

Grid handles rows and columns at the same time, which makes it ideal for full page layouts. You define the tracks and let items flow into them.

.gallery {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
}

This creates three equal columns that share the available width, with 16px gaps between cells. The items flow into the grid in order, filling row after row. The fr unit means fraction of the free space, so three fr units split the container evenly.

Choosing Between Flex and Grid

  • Use flexbox for one-dimensional rows or columns, alignment, and distributing items.
  • Use grid for two-dimensional layouts where rows and columns matter together.
  • Flexbox controls alignment on two axes but arranges in only one dimension.
  • Both coexist happily: a grid area can contain its own flex row.

A Practical Hybrid

.page {
    display: grid;
    grid-template-columns: 240px 1fr;
    gap: 24px;
}

.page nav {
    display: flex;
    flex-direction: column;
}

Here grid draws a sidebar and a main column, while flex stacks the navigation links vertically inside the sidebar. Combining the two matches the natural shape of most interfaces.

Key Points

  • Flexbox arranges items in one dimension with rich alignment control.
  • Grid places items in rows and columns at the same time.
  • repeat, fr units, and gap make grid layouts concise.
  • Use flex for single-direction layouts and grid for full surfaces.
Share this post:

Comments (0)

Please login or register to comment.