CSS Grid Cheat Sheet
Grid lays items out in rows and columns at once. Start with display: grid on the parent.
Container properties
| Property | Example | What it does |
|---|---|---|
grid-template-columns | repeat(3, 1fr) | Defines the columns |
grid-template-rows | auto 1fr auto | Defines the rows |
gap | 1rem | Space between rows and columns |
grid-template-areas | "header header" "side main" | Names regions of the layout |
justify-items | start, center, stretch | Aligns items horizontally inside cells |
align-items | start, center, stretch | Aligns items vertically inside cells |
grid-auto-flow | row, dense | How automatic items are placed |
Item properties
| Property | Example | What it does |
|---|---|---|
grid-column | 1 / 3 | Spans from line 1 to line 3 |
grid-column | span 2 | Spans two columns |
grid-row | 2 / 4 | Spans rows |
grid-area | header | Puts the item in a named area |
Useful units and functions
fris a share of the free space.1fr 2frgives the second column twice the width.minmax(200px, 1fr)sets a minimum and a maximum size.repeat(3, 1fr)avoids writing the same value three times.
Patterns
Responsive cards without media queries
.cards { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); }
Page layout with header, sidebar, content and footer
.page {
display: grid;
grid-template-columns: 16rem 1fr;
grid-template-areas: "header header" "side main" "footer footer";
}
header { grid-area: header; }
aside { grid-area: side; }
main { grid-area: main; }
footer { grid-area: footer; }
Use auto-fill to keep empty tracks and auto-fit to collapse them, so that items stretch.