CSS Flexbox vs Grid: When to Use Which
The definitive guide to choosing between Flexbox and Grid — with a simple decision framework.
The Simple Rule
- Flexbox = one-dimensional layout (row OR column)
- Grid = two-dimensional layout (rows AND columns)
If your layout only needs to work in one direction, use Flexbox. If it needs to align items in both rows and columns simultaneously, use Grid.
Use Flexbox When...
Navigation bars
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}Centering anything
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}Card rows that wrap
.card-row {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.card {
flex: 1 1 300px; /* Grow, shrink, min-width */
}Space between items
.footer {
display: flex;
justify-content: space-between;
}
.button-group {
display: flex;
gap: 0.5rem;
}Use Grid When...
Page layouts
.page {
display: grid;
grid-template-columns: 250px 1fr 300px;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }Equal-width columns
.grid-3 {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}Responsive grids (no media queries!)
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
/* Cards auto-resize from 250px to fill available space */Overlapping elements
.stack {
display: grid;
place-items: center;
}
.stack > * {
grid-area: 1 / 1; /* All children overlap */
}Common Patterns
Holy Grail Layout (Grid)
body {
display: grid;
grid-template: auto 1fr auto / 200px 1fr 200px;
min-height: 100vh;
}
header, footer { grid-column: 1 / -1; }Sidebar + Content (Grid)
.layout {
display: grid;
grid-template-columns: minmax(200px, 25%) 1fr;
gap: 2rem;
}Inline Form (Flexbox)
.form-row {
display: flex;
gap: 0.5rem;
align-items: flex-end;
}
.form-row input { flex: 1; }
.form-row button { flex-shrink: 0; }Decision Framework
| Scenario | Use |
|---|---|
| Navbar / toolbar | Flexbox |
| Center something | Flexbox or Grid |
| Page layout (header/sidebar/content) | Grid |
| Equal columns | Grid |
| Responsive card grid | Grid |
| Button group | Flexbox |
| Form layout | Grid for labels+inputs, Flexbox for inline |
| Overlapping elements | Grid |
| Unknown number of items in a row | Flexbox |
| Precise 2D placement | Grid |
Pro Tips
- You can nest them. Grid for the page layout, Flexbox for components inside grid cells.
- gap works in both. Stop using margins for spacing between flex/grid items.
- place-items: center is the fastest way to center with Grid.
- auto-fill vs auto-fit: auto-fill creates empty tracks, auto-fit collapses them.
More tools: Try our free Color Converter and Word Counter.