CSS Weekly #2: Flexbox vs Grid - When to Use Which?
CSS Weekly #2: Flexbox vs Grid - When to Use Which? 🤔
Hey ,
Last week we explored CSS Grid fundamentals. This week, let's tackle the age-old question: Grid or Flexbox?
Spoiler: It's not Grid OR Flexbox. It's Grid AND Flexbox!
The Simple Rule
- Flexbox: One-dimensional layouts (rows OR columns)
- Grid: Two-dimensional layouts (rows AND columns)
But it's more nuanced than that...
Use Flexbox When:
1. Content determines layout
.nav {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
Perfect for navigation where items should flow naturally.
2. You need alignment control
.card {
display: flex;
flex-direction: column;
justify-content: space-between;
}
3. Content needs to be flexible
.toolbar button {
flex: 1; /* Equal width buttons */
}
Use Grid When:
1. You have a defined layout structure
.dashboard {
display: grid;
grid-template-columns: 250px 1fr 300px;
}
2. You need precise placement
.featured {
grid-column: 1 / -1; /* Span entire width */
grid-row: 2;
}
3. Complex responsive layouts
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
🎨 Real Example: Card Component
Here's how I combine both:
/* Grid for overall layout */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
}
/* Flexbox for card internals */
.card {
display: flex;
flex-direction: column;
}
.card-footer {
margin-top: auto; /* Push to bottom */
display: flex;
justify-content: space-between;
align-items: center;
}
Pro Tip: Subgrid is Amazing!
If you're using Grid, don't miss subgrid (now in all modern browsers):
.card {
display: grid;
grid-template-rows: subgrid;
grid-row: span 3;
}
This aligns nested grid items with the parent grid. Game changer!
📊 Quick Decision Matrix
| Need | Use |
|---|---|
| Navigation bar | Flexbox |
| Page layout | Grid |
| Card internals | Flexbox |
| Card gallery | Grid |
| Form layout | Grid |
| Button group | Flexbox |
Community Question
"Should I use Grid for everything now that it's widely supported?" - Marcus
Great question! While Grid is powerful, Flexbox is often simpler for one-dimensional layouts. Use the right tool for the job.
Today's sponsor: CSS Scan - Instantly check the CSS of any element. CSS Weekly readers get 30% off!
Next week: CSS Custom Properties (aka CSS Variables) deep dive!
— Sarah from CSS Weekly
Add a comment: