Back to CSS
CSS
easy
very high
junior

When should you use Flexbox versus CSS Grid?

Flexbox is one-dimensional (a row OR a column). Grid is two-dimensional (rows AND columns at once). Use flex for component layouts and toolbars, grid for page templates, dashboards, and any 2D alignment.

5 min read·~10 min to think through

Both are modern layout systems; they're complementary, not competitors.

Flexbox lays out items along one axis at a time. You think in terms of: main axis vs cross axis, justify vs align, wrap vs nowrap. Perfect for:

  • Toolbars and navbars (icons + spacing).
  • Form rows.
  • Vertical centering of one block.
  • Component-level layouts where children flow in a single direction.

Grid lays out items in two dimensions simultaneously. You think in terms of: rows, columns, tracks, areas. Perfect for:

  • Page templates (header / sidebar / main / footer with grid-template-areas).
  • Dashboards with consistent gutters.
  • Image galleries and product grids.
  • Aligning items across both axes (which flex requires nesting to achieve).

Practical heuristic: if you find yourself nesting flex containers to align items in two dimensions, you wanted grid. If you find yourself fighting grid to handle dynamic-sized children, you wanted flex.

Combine them freely: page-level grid, component-level flex inside each grid cell.

Code

css
.toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
}
.toolbar .spacer { margin-left: auto; } /* push the right group */
Flex toolbar
css
.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  grid-template-areas:
    "sidebar header"
    "sidebar main";
  height: 100vh;
}
.page > header  { grid-area: header; }
.page > aside   { grid-area: sidebar; }
.page > main    { grid-area: main; }
Grid page layout with named areas

Follow-up questions

  • How do `auto-fit` and `auto-fill` differ in `repeat()`?
  • What does `subgrid` solve?
  • When does `flex: 1` produce different results than `flex: auto`?

Common mistakes

  • Using grid where flex would do — heavier mental model for one-dimensional cases.
  • Setting a child's `width` rigidly inside a flex container and breaking wrapping.
  • Forgetting `min-width: 0` on flex children that contain text — overflow ensues.

Performance considerations

  • Both are zero-cost layout primitives. Layout cost depends on tree depth and dynamic sizes.

Edge cases

  • `gap` works in both flex and grid — modern enough to drop margin hacks.
  • RTL: use logical alignment (`start` / `end`) instead of `left` / `right`.

Real-world examples

  • Most dashboard apps use grid for the shell and flex within each pane (toolbar, list rows).

Senior engineer discussion

Senior signal: discuss container queries, intrinsic-sized grid tracks (`auto-fit minmax`), and how subgrid finally makes deeply nested grids align.

Related questions