The One-Sentence Rule
Flexbox is for rows or columns. Grid is for rows and columns simultaneously.
Laying out items in a single direction — a navbar, a row of cards, a vertical sidebar — use Flexbox. Controlling items in two dimensions at once — a dashboard, a photo gallery, a page layout with header, sidebar, main, and footer — use Grid.
Flexbox in Practice
/* Horizontal nav with items spread out */
.navbar {
display: flex;
justify-content: space-between; /* horizontal distribution */
align-items: center; /* vertical alignment */
}
/* Equal-width columns that wrap on small screens */
.card-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.card { flex: 1 1 280px; }
Grid in Practice
/* Dashboard layout with named areas */
.dashboard {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
grid-template-rows: 60px 1fr 40px;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
/* Auto-fill responsive gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 8px;
}
They Are Complementary
The page layout uses Grid; content inside each grid cell often uses Flex. Grid defines macro structure (sidebar, main, header). Flex aligns items within each section (nav links, card contents, form rows).
Quick Decision Guide
| Scenario | Use |
|---|---|
| Navigation bar | Flexbox |
| Card row that wraps | Flexbox |
| Photo gallery (auto-fill) | Grid |
| Page layout with sidebar | Grid |
| Form with aligned labels/inputs | Grid |
| Center one element | Either (Flex simpler) |