CSS Grid vs Flexbox: When to Use Which (with Examples)
“Should I use Grid or Flexbox?” is one of the most common CSS layout questions. The short answer: Flexbox is one-dimensional, Grid is two-dimensional. This guide explains what that means in practice and gives you clear rules for choosing.
The core difference
Flexbox lays out items along a single axis — either a row or a column. You control how items grow, shrink, and align along that one line.
Grid lays out items on a grid of rows and columns at the same time. You define the structure (tracks) and place items into cells.
If your layout is “a line of things,” reach for Flexbox. If it’s “a table-like structure of rows and columns,” reach for Grid.
When to use Flexbox
Flexbox shines for components and content that flow in one direction:
- Navigation bars
- Button groups
- A row of cards that should wrap
- Centering a single element
- Toolbars and form rows
Example — a navbar with a logo on the left and links on the right:
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
justify-content distributes along the main axis; align-items aligns on the cross axis. That’s the whole mental model.
When to use Grid
Grid is built for page-level and component layouts where you control both dimensions:
- Photo galleries
- Dashboards
- Product card grids
- Magazine-style layouts
- Any “place this here, that there” structure
Example — a responsive card grid with no media queries:
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}
This creates as many 200px+ columns as fit, sharing leftover space equally. The grid reflows automatically as the viewport changes.
Can I use both? Yes — and you should
They are not competitors. The most common real-world pattern: Grid for the overall page layout, Flexbox for the components inside each grid cell.
.page {
display: grid;
grid-template-columns: 250px 1fr; /* sidebar + main */
}
.card {
display: flex;
flex-direction: column;
justify-content: space-between;
}
The page skeleton is a 2D problem (Grid). The card’s internal stacking is a 1D problem (Flexbox).
Quick decision rule
- One row or one column of items? Flexbox.
- Rows and columns aligned together? Grid.
- Content-driven sizing (let items decide)? Lean Flexbox.
- Layout-driven sizing (you define the structure)? Lean Grid.
Centering: the famous case
Both can center, but Flexbox is the shortest:
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
Grid can do it in one fewer line with place-items: center, which is handy too.
Build it visually
Memorizing every property takes time. Instead, build the layout visually and copy the output: try the CSS Grid Generator for grids, or the CSS Flexbox Generator for flex containers. Both show a live preview and give you copy-ready CSS.
Generate this CSS visually — no coding required. Instant live preview.
Open Tool →