CSS Grid Cheat Sheet

Grid lays items out in rows and columns at once. Start with display: grid on the parent.

Container properties

PropertyExampleWhat it does
grid-template-columnsrepeat(3, 1fr)Defines the columns
grid-template-rowsauto 1fr autoDefines the rows
gap1remSpace between rows and columns
grid-template-areas"header header" "side main"Names regions of the layout
justify-itemsstart, center, stretchAligns items horizontally inside cells
align-itemsstart, center, stretchAligns items vertically inside cells
grid-auto-flowrow, denseHow automatic items are placed

Item properties

PropertyExampleWhat it does
grid-column1 / 3Spans from line 1 to line 3
grid-columnspan 2Spans two columns
grid-row2 / 4Spans rows
grid-areaheaderPuts the item in a named area

Useful units and functions

  • fr is a share of the free space. 1fr 2fr gives 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.

↑ ↓ navigateEnter openEsc close