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;
}
UnitMeaning
frA fraction of leftover space — the workhorse
autoSize to content
min-content/max-contentContent'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.

Flexbox Responsive design

Last refreshed 2026-09-17.