CSS Grid replaced countless JavaScript layout hacks. At Google, Grid is our go-to for any 2D layout challenge.
Grid vs Flexbox
Flexbox: 1-dimensional (row OR column). Grid: 2-dimensional (rows AND columns simultaneously). Use Flexbox for components, Grid for page layouts.
The Fundamentals
.dashboard {
display: grid;
grid-template-columns: 250px 1fr 300px;
grid-template-rows: 60px 1fr 40px;
grid-template-areas:
"sidebar header aside"
"sidebar main aside"
"sidebar footer aside";
gap: 16px;
height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }Responsive Without Media Queries
/* Auto-fill: creates as many columns as fit */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
}
/* Auto-fit: stretches items to fill space */
.stretch-grid {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}Advanced Techniques
Subgrid
Lets child grids align to the parent grid's tracks. Game-changer for card layouts where you need content to align across cards.
.card {
display: grid;
grid-template-rows: subgrid;
grid-row: span 3; /* Card spans 3 rows of parent */
}Dense Packing
.masonry-like {
grid-auto-flow: dense; /* Fill holes in the grid */
}Common Gotchas
1frrespects content size — useminmax(0, 1fr)to truly divide space equally- Grid items stretch by default — use
place-self: startto prevent it - Grid areas must form a rectangle — L-shapes won't work