CSS Grid
Two-dimensional layout: tracks, the fr unit, placement by line or area, and responsive grids without media queries.
Defining tracks
.grid {
display: grid;
grid-template-columns: 200px 1fr 2fr;
grid-template-rows: auto;
gap: 16px;
}| Unit | Meaning |
|---|---|
fr | A fraction of leftover space β the workhorse |
auto | Size to content |
min-content/max-content | Content's smallest / natural width |
minmax(200px, 1fr) | At least 200px, at most one fraction |
π‘
1fr is minmax(auto, 1fr), which refuses to shrink below content and can overflow. Write minmax(0, 1fr) when you need a track that genuinely shrinks.Placing items
/* by line number: lines are counted, not tracks */
.panel { grid-column: 1 / 3; grid-row: 1; }
/* by named area */
.page {
grid-template-areas:
'head head'
'side main'
'foot foot';
grid-template-columns: 240px 1fr;
}
.page > header { grid-area: head; }Items are placed automatically into the next free cell. Use grid-auto-flow: dense if you want later small items to backfill gaps β at the cost of visual order not matching source order, which can hurt accessibility.
Responsive without media queries
.cards {
display: grid;
gap: 16px;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
}auto-fill packs as many tracks as fit (leaving empty tracks if few items). auto-fit collapses empty tracks so remaining items stretch to fill the row β usually what you want for card lists.
β οΈ
Grid changes reading order only if you place items explicitly. Always check keyboard tab order matches visual order when using explicit placement.
FAQ
Can I nest grids?
Yes, and descendants can even align to a parent grid with subgrid where supported β ideal for aligning card internals across a row.
How do I centre one item?
place-items: center on the container (or place-self on the item) is the shortest reliable answer.Related
Last refreshed 2026-09-17.