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-contentaligns along the main axis,align-itemsalong the cross axis, andflex: 1means grow to fill. - Grid:
grid-template-columns,frunits,gap, and named areas (grid-template-areas). - Responsive cards with no media queries:
repeat(auto-fill, minmax(200px, 1fr)). gapworks 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 withjustify-contentandalign-itemsset tocenter). - Why doesn't
z-indexwork on my element? It needs a positioned element or a flex/grid item, and it only competes within the same stacking context.transform,opacity < 1andisolation: isolatecreate 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.