CSS Grid and Flexbox: A Practical Comparison
Every frontend interview asks some variation of "Grid vs Flexbox." After building layouts for five years, here's the mental model that actually works.
The Simple Rule
Flexbox: One dimension (row OR column) Grid: Two dimensions (rows AND columns)
That's it. Everything else flows from this.
Flexbox in Practice
Perfect for navigation bars, card layouts within a row, and centering content.
/* Navigation bar */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
.nav-links {
display: flex;
gap: 2rem;
}
/* Card container */
.card-row {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
}
.card {
flex: 1 1 300px; /* grow, shrink, basis */
max-width: 400px;
}
Flexbox Alignment Tricks
/* Perfect centering */
.centered {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Push last item to end */
.header {
display: flex;
gap: 1rem;
}
.header .logout {
margin-left: auto;
}
/* Equal height cards */
.card-container {
display: flex;
align-items: stretch;
}
Grid in Practice
Perfect for page layouts, dashboards, gallery grids, and anything with explicit rows and columns.
/* Basic page layout */
.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; }
/* Photo gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
/* Dashboard widgets */
.dashboard {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto;
gap: 1.5rem;
}
.widget-large {
grid-column: span 2;
grid-row: span 2;
}
Responsive Grid Without Media Queries
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr));
gap: 1rem;
}
This single line creates a responsive grid that works from mobile to desktop.
When to Use Which
Use Flexbox
- Navbar items
- Button groups
- Form input + button
- Centering elements
- Equal-height siblings
Use Grid
- Page structure
- Card grids
- Dashboard layouts
- Image galleries
- Any table-like layout
Combining Both
They work great together:
/* Grid for overall layout */
.page {
display: grid;
grid-template-columns: 1fr 3fr;
gap: 2rem;
}
/* Flexbox for sidebar items */
.sidebar {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Flexbox for each nav item */
.nav-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
Common Mistakes
- Using Grid for single-row layouts - Flexbox is simpler
- Using Flexbox for actual grids - Grid handles gaps and alignment better
- Fighting the browser - If it feels hacky, you're using the wrong tool
Both are powerful. Pick based on what you're building, not habit.