Flexbox vs Grid
When to use each layout system
Two Layout Systems
CSS offers two powerful layout systems: Flexbox and CSS Grid. Both solve layout problems, but they approach them differently. Understanding when to use each is key to writing clean, maintainable layouts.
Flexbox: ONE-dimensional layout (row OR column)
Grid: TWO-dimensional layout (rows AND columns)
┌─────────────┐ ┌──────┬──────┬──────┐
│ A │ B │ C │ │ A │ B │ C │
└─────────────┘ ├──────┼──────┼──────┤
Flexbox row │ D │ E │ F │
└──────┴──────┴──────┘
Grid (rows & columns)Flexbox Strengths
Flexbox excels at content-driven layouts where the size of items should determine the layout. It is ideal for navigation bars, centering content, and distributing space.
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
/* Items take only the space they need */
.nav-link { padding: 8px 16px; }.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}Grid Strengths
Grid excels at layout-driven designs where you define the structure first and place items into it. It is ideal for page layouts, card grids, and complex arrangements.
.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 24px;
}Side by Side
Feature Flexbox Grid ────────────────────────────────────────── Dimensions 1D 2D Content-driven ✓ Excellent Possible Layout-driven Possible ✓ Excellent Alignment ✓ Both axes ✓ Both axes Gap ✓ gap ✓ gap Named areas ✗ ✓ grid-template-areas Item placement Order-based Row + Column Wrapping flex-wrap auto-fit / auto-fill Overlap Difficult Easy (grid-area) Browser support ✓ All modern ✓ All modern ────────────────────────────────────────── ✓ = strength ✗ = not available
Using Both Together
The best layouts often combine both systems. Use Grid for the overall page structure, and Flexbox for individual component layouts within grid cells.
/* Page layout with Grid */
.page {
display: grid;
grid-template-columns: 1fr 3fr;
gap: 24px;
}
/* Navigation within sidebar uses Flexbox */
.sidebar nav {
display: flex;
flex-direction: column;
gap: 8px;
}
/* Card content uses Flexbox */
.card {
display: flex;
flex-direction: column;
justify-content: space-between;
}Summary
Use Flexbox for components
Navigation bars, button groups, centering content, and any one-dimensional arrangement of items.
Use Grid for layouts
Page structure, card grids, dashboards, and any two-dimensional layout where you need precise control over rows and columns.
Combine them freely
Grid and Flexbox are complementary, not competing. Use Grid for the macro layout and Flexbox for micro layouts within grid cells.