CSS Grid Layout has revolutionized how we build web layouts. Unlike Flexbox, which is one-dimensional, Grid gives you full two-dimensional control over your layouts.
Basic Concepts
Grid Container
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 1rem;
}
Grid Items
.item {
grid-column: 1 / 3; /* Span from line 1 to line 3 */
grid-row: 1 / 2;
}
Named Grid Areas
One of the most powerful features is named grid areas:
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-columns: 250px 1fr 1fr;
grid-template-rows: auto 1fr auto;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Responsive Without Media Queries
Use auto-fit and minmax() to create responsive grids without a single media query:
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
Auto-fill vs Auto-fit
auto-fill: Creates as many tracks as possible, even if emptyauto-fit: Collapses empty tracks, allowing items to stretch
Practical Examples
Card Layout
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1.5rem;
padding: 2rem;
}
Holy Grail Layout
.page {
display: grid;
grid-template:
"header" auto
"nav" auto
"main" 1fr
"footer" auto
/ 1fr;
min-height: 100vh;
}
Browser Support
CSS Grid is supported in all modern browsers. With gap support added in recent versions, there's no reason not to use Grid in production today.
CSS Grid is the first CSS module that truly thinks in two dimensions. It changes not just how we write CSS, but how we think about layout.