CSS Grid
Two-dimensional layout with CSS Grid
What you'll learn
Define grid containers with explicit rows and columns
Place items across the grid using line numbers and named areas
Create responsive layouts with auto-fit, auto-fill, and minmax()
Control gutters with the gap shorthand property
Align and distribute content with align-items, justify-items, and place-items
Build complex magazine-style layouts with overlapping grid items
CSS Grid is a two-dimensional layout system.
Basic Grid
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 16px;
}
Grid Areas
.layout {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}
Auto-fit / Minmax
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 16px;
}
Next Steps
- Flexbox — One-dimensional layout
- Tailwind Grid — Grid in Tailwind
Key Takeaways
CSS Grid is a two-dimensional layout system for controlling both rows and columns simultaneously
Grid lines are numbered from 1, and items can span multiple tracks using grid-column and grid-row
Named grid areas (grid-template-areas) make layout intent readable directly in CSS
auto-fit and minmax() create responsive grids that adapt to available space without media queries
The fr unit distributes available space proportionally, similar to flex-grow in Flexbox
Grid items can overlap other items, enabling complex magazine-style layouts with z-index control