Skip to main content
11

Flexbox vs Grid: when to use which?

EasyCSSLayout

What's the difference between Flexbox and CSS Grid, and when do you use each?

TL;DR

Flexbox is one-dimensional: it lays items out along a single row or column and is driven by the content (items grow and shrink to fit). Grid is two-dimensional: you define rows and columns and place items into that structure, so it's driven by the layout. Use Flexbox for components (navbars, button groups, centering, a row of cards that wraps). Use Grid for page-level layouts and anything that must line up in both directions.

Key points

  • Flexbox: justify-content aligns along the main axis, align-items along the cross axis, and flex: 1 means grow to fill.
  • Grid: grid-template-columns, fr units, gap, and named areas (grid-template-areas).
  • Responsive cards with no media queries: repeat(auto-fill, minmax(200px, 1fr)).
  • gap works in both.
  • They combine well: Grid for the page skeleton, Flexbox inside each cell.
  • Subgrid lets nested items align to the parent grid's tracks (card titles and footers lining up across cards).

Example

css
/* Flexbox: a header bar */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

/* Grid: page layout */
.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-areas: 'sidebar main';
}

/* Grid: responsive card list */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 1rem;
}

Common follow-ups

  • How do you center a div? display: grid; place-items: center (or flex with justify-content and align-items set to center).
  • Why doesn't z-index work on my element? It needs a positioned element or a flex/grid item, and it only competes within the same stacking context. transform, opacity < 1 and isolation: isolate create new ones.

What interviewers look for

Tip

"One dimension, content-out" vs "two dimensions, layout-in", with a concrete example of each.

  • Red flag: "Grid replaced Flexbox", or building a 2D layout from nested flex rows with fixed widths.

Was this helpful?