CSS Grid Mastery
22 min read
CSS Gridgrid-template-areasfr unitrepeat()minmax()auto-fillauto-fitsubgrid
Two-Dimensional Layouts
CSS Grid is designed for two-dimensional layouts — rows AND columns simultaneously. It's the most powerful layout system in CSS.
Grid vs Flexbox — When to Use Which
| Feature | Flexbox | CSS Grid |
|---|---|---|
| Dimensions | 1D (row OR column) | 2D (rows AND columns) |
| Content-first | ✅ Items determine layout | ❌ Grid defines layout |
| Layout-first | ❌ Can be hacked | ✅ Define areas, place items |
| Equal heights | Only in same row | Across entire grid |
| Overlapping items | Not possible | ✅ Grid areas can overlap |
| Best for | Navbars, card rows, toolbars | Page layouts, dashboards, galleries |
Core Concepts
Tracks: Rows and columns defined by grid-template-rows and grid-template-columns.
fr unit: A fraction of available space. 1fr 2fr means the second column gets twice the space.
repeat(): Shorthand for repeated tracks: repeat(3, 1fr) = three equal columns.
minmax(): Set minimum and maximum track sizes: minmax(200px, 1fr).
auto-fill vs auto-fit:
| Keyword | Behavior | Empty Tracks |
|---|---|---|
auto-fill | Creates as many tracks as fit | Keeps empty tracks (space reserved) |
auto-fit | Creates as many tracks as fit | Collapses empty tracks (items stretch) |
Grid Template Areas
The most readable way to define layouts:
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar content aside"
"footer footer footer";
grid-template-columns: 250px 1fr 200px;
grid-template-rows: auto 1fr auto;
}Subgrid
Subgrid allows a child grid to inherit its parent's track definitions, solving the alignment problem across nested grids.