CSS layouts explained: flexbox and grid without the panic
Two layout systems, one mental model. Visual examples of when to reach for flexbox and when a grid saves the day.
On this page
Beginners treat flexbox and grid as two rival systems to master separately. They are one idea at two scales: arrange things along one line, or arrange things in two dimensions at once. Get that distinction clear and most layout panic disappears.
The one-line mental model
Use flexbox when the content should flow in one direction and the items themselves decide the sizes — navbars, button rows, chip lists. Use grid when the structure decides the sizes — page scaffolding, card galleries, forms with aligned columns.
/* Flexbox: one line, content-sized */
.toolbar {
display: flex;
align-items: center;
gap: 0.75rem;
}
/* Grid: two dimensions, structure-sized */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
gap: 1rem;
}The gallery pattern you will reuse forever
The single most useful grid recipe in production work: repeat(auto-fill, minmax(16rem, 1fr)) — "make as many columns as fit, each at least 16rem, share the rest." No media queries, works from phones to walls of monitors. Card grids, image galleries, and footer link columns all reduce to it.
When they combine
Real pages nest them: a grid lays out the page regions, flexbox arranges the content inside each region. A card gallery (grid) where each card header is a title plus an icon at the far end (flexbox) — that combination covers an enormous share of real-world layouts.
| Question | If yes |
|---|---|
| Do items flow in one row or column? | Flexbox |
| Should content size drive the layout? | Flexbox |
| Do rows AND columns need to align? | Grid |
| Is it page scaffolding or a card gallery? | Grid |
| Do both apply (region + inner row)? | Nest grid and flexbox |
Practice path
Rebuild three things you already use daily: a navbar, a card grid, and a simple pricing page. Then read our UI design starter guide for the spacing and hierarchy side of the same skill.
Found this useful? Share it.