Code Reference

CSS Grid

CSS · Reference cheat sheet

CSS Grid

CSS · Reference cheat sheet


📋 Overview

CSS Grid is a two-dimensional layout system for rows and columns. Define tracks on a container with grid-template-*, place items with line-based or area-based positioning, and control gaps and alignment. Use Grid for page shells, card galleries, dashboards, and any UI where rows and columns interact. Prefer Flexbox for simple one-axis distribution inside a grid cell.

Subgrid (grid-template-*: subgrid) lets nested grids inherit parent tracks for aligned columns across components.

🔧 Core concepts

Container properties

PropertyRole
display: grid | inline-gridEstablish grid formatting context
grid-template-columns / rowsTrack list (fr, px, %, minmax(), repeat())
grid-template-areasNamed rectangular areas
grid-auto-columns / rowsImplicit track sizing
grid-auto-flowrow | column | dense
gap / row-gap / column-gapGutters
justify-items / align-itemsDefault cell alignment
justify-content / align-contentTracks inside the container
place-items / place-contentShorthands

Item properties

PropertyRole
grid-column / grid-rowLine start / end (1 / 3, span 2)
grid-areaArea name or four-line shorthand
justify-self / align-selfPer-item alignment
orderVisual order (use carefully)

Track sizing functions

FunctionUse
frShare free space
minmax(min, max)Flexible bounds
repeat(n, …) / repeat(auto-fit, …) / auto-fillPatterns
fit-content()Clamp to content up to a limit
min-content / max-content / autoContent-based tracks

💡 Examples

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: 1rem;
}

Holy grail with areas

.page {
  display: grid;
  grid-template-columns: 12rem 1fr 12rem;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header header"
    "nav    main   aside"
    "footer footer footer";
  min-block-size: 100dvh;
  gap: 1rem;
}

.header { grid-area: header; }
.nav    { grid-area: nav; }
.main   { grid-area: main; }
.aside  { grid-area: aside; }
.footer { grid-area: footer; }

@media (max-width: 48rem) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas:
      "header"
      "nav"
      "main"
      "aside"
      "footer";
  }
}

Span and dense packing

.board {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-flow: dense;
  gap: 0.5rem;
}

.board .wide {
  grid-column: span 2;
}

Align within cells

.cell-center {
  display: grid;
  place-items: center;
  min-block-size: 10rem;
}

⚠️ Pitfalls

  • Using only fixed px columns that overflow small viewports—prefer minmax + auto-fit/fr.
  • Confusing auto-fit (collapses empty tracks) with auto-fill (keeps empty tracks).
  • Forgetting that percentage row heights need a definite container block size.
  • Over-nesting grids when one template + areas would suffice.
  • Relying on order or visual placement that diverges from DOM order for keyboard users.

On this page