CSS Grid vs. Flexbox: When to Use Each
Grid and Flexbox aren't rivals — they solve different problems. A simple rule of thumb, with examples, for choosing the right layout tool every time.
Both Flexbox and Grid are modern CSS layout systems, and beginners often wonder which to learn. The answer is both — but for different jobs.
The one-line rule
- Flexbox is for laying out items in a single direction — a row or a column.
- Grid is for two dimensions at once — rows and columns together.
If you’re arranging things along one axis, reach for Flexbox. If you’re building a true grid where rows and columns must align, reach for Grid.
Flexbox in practice
A navigation bar — items in a row, spaced apart:
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
Flexbox shines when item sizes are content-driven and you want them to grow, shrink, or wrap naturally.
Grid in practice
A responsive card gallery — equal columns that reflow:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1.5rem;
}
That single grid-template-columns line creates as many equal columns as fit, each at least 240px wide — no media queries required.
Use them together
They compose. A common pattern: Grid for the page skeleton (header, sidebar, main, footer), Flexbox for the components inside each region.
.layout {
display: grid;
grid-template-columns: 250px 1fr;
}
Quick decision guide
- Aligning a few items in a row or column? Flexbox.
- Need items to wrap based on available space? Flexbox (or auto-fill Grid).
- Building a layout where columns and rows must line up? Grid.
- Overall page structure? Grid.
Learn the one-direction-vs-two-dimensions distinction and the choice becomes automatic.
Tagged
Keep reading
Getting Started with TypeScript: A Practical Guide
TypeScript adds a safety net to JavaScript without slowing you down. Here's how to set it up, the handful of concepts that matter, and how to adopt it gradually.
Understanding the JavaScript Event Loop
Why does JavaScript feel single-threaded yet handle so much at once? The event loop is the answer. Here's a clear mental model with examples you can run.
HTTPS Explained: What Happens When You Visit a Site
The padlock in your address bar hides a clever handshake. Here's what actually happens when you load an HTTPS site — encryption, certificates, and trust.