Flexbox vs Grid: when do you use each?
Flexbox: one dimension
Lays items out in a row or a column. The content drives the sizes: items grow and shrink to share space.
justify-contentaligns on the main axis,align-itemson the cross axis,gapspaces items.flex: 1means grow and shrink equally from a zero basis.flex-wrap: wraplets items move to new lines, but each line is laid out on its own.- Best for: navigation bars, toolbars, button groups, centring, a card's internal layout.
Grid: two dimensions
Defines rows and columns at once; the layout drives where content goes.
grid-template-columns: repeat(3, 1fr);frshares the free space.grid-template-areasnames regions for readable page layouts.repeat(auto-fill, minmax(200px, 1fr))gives a responsive grid with no media queries.subgridlets nested items line up with the parent's tracks (supported in all modern browsers).- Best for: page layouts, card galleries, dashboards, forms that align labels and inputs.
They combine well: Grid for the page, Flexbox inside each component.
Example
css
/* Responsive card grid with no media query */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 16px;
}
/* Page layout with named areas */
.page {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-areas: "header header" "sidebar main";
min-height: 100dvh;
}
.page > header { grid-area: header; }
/* Toolbar: push the last button to the right */
.toolbar { display: flex; align-items: center; gap: 8px; }
.toolbar .spacer { margin-left: auto; }
/* Perfect centring */
.center { display: grid; place-items: center; }Follow-up questions interviewers ask
Try answering each one before you open it.
Why does a flex item overflow instead of shrinking?
Flex items default to min-width: auto, so they will not shrink below their content's width (a long word or a wide child). Set min-width: 0 (or overflow: hidden) on the item to allow shrinking, which is the usual fix for text truncation with text-overflow: ellipsis inside flex rows.