Grid vs Flexbox?

Flexbox is one-dimensional: it lays items out along a single row or column and lets the content decide sizes. Grid is two-dimensional: it defines rows and columns together and places items into that structure. Use Flexbox for components that flow in one direction, Grid for layouts where things must line up both ways, and combine them freely.

Comparison

FlexboxGrid
DimensionsOne (row or column)Two (rows and columns)
ApproachContent-out: items size the layoutLayout-in: tracks size the items
WrappingEach wrapped line is independent, so columns do not alignItems always align to shared tracks
PlacementSource order (plus order)Auto-placement, line numbers, named areas, overlapping
Best forNavbars, toolbars, button groups, centering, tag listsPage layouts, dashboards, galleries, forms, card grids

Rules of thumb

  • If you want items to line up in both directions, use Grid.
  • If items should be as wide as their content and simply flow, use Flexbox.
  • A wrapping card list where the last row should keep the same widths: Grid (repeat(auto-fill, minmax(...))).
  • A navbar with logo left and links right: Flexbox.
  • Overlapping elements (text over an image) without absolute positioning: Grid (grid-area: 1 / 1 on both).

They work together

Typical page: Grid for the overall layout, Flexbox inside each card or header. Both share gap and the Box Alignment properties (justify-content, align-items).

Interview tip

Avoid "Grid is better" answers; explain the one vs two dimensional distinction and give an example of each.

Code example

html
1<style>
2 body { font-family: system-ui; }
3 .flex { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 18px; }
4 .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 8px; }
5 .flex div, .grid div { border: 2px solid #0b1020; padding: 8px; border-radius: 6px; background: #dbeafe; }
6 .flex div { flex: 1 1 110px; }
7 .stack { display: grid; width: 240px; margin-top: 18px; }
8 .stack > * { grid-area: 1 / 1; } /* overlap without position: absolute */
9 .stack p { align-self: end; margin: 0; padding: 8px; color: white; background: rgb(11 16 32 / .7); }
10</style>
11<p><b>Flexbox:</b> the last row stretches differently</p>
12<div class="flex"><div>One</div><div>Two</div><div>Three</div><div>Four</div><div>Five</div></div>
13<p><b>Grid:</b> every item lines up with the columns</p>
14<div class="grid"><div>One</div><div>Two</div><div>Three</div><div>Four</div><div>Five</div></div>
15<div class="stack">
16 <img src="https://picsum.photos/id/1041/480/240" alt="Forest path" width="240" height="120">
17 <p>Grid overlap caption</p>
18</div>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app