CSS Grid

Two-dimensional layout with rows and columns: page shells, galleries, dashboards and complex alignment.

Beginner · about 5 hours · difficulty 3/5

Learn first: Flexbox

CSS Grid controls rows and columns together. Where flexbox lets content decide its size, grid lets the container define a structure that content slots into.

Core syntax

  • display: grid plus grid-template-columns: 200px 1fr gives a sidebar layout. The fr unit divides remaining space.
  • repeat(auto-fill, minmax(220px, 1fr)) creates a responsive gallery with no media queries: as many columns as fit, each at least 220px.
  • Place items with line numbers (grid-column: 1 / -1 spans everything) or with named template areas, which read like an ASCII map of the layout.
  • gap, place-items and place-content handle spacing and alignment.

Useful details

  • auto-fill keeps empty tracks; auto-fit collapses them so items stretch.
  • Implicit rows are created automatically; grid-auto-rows sizes them.
  • Subgrid (grid-template-columns: subgrid) lets nested components align to the parent grid, which fixes the classic "card footers do not line up" problem.
  • Visual order changes (placing items out of source order) do not change keyboard or screen reader order, so keep the DOM order logical.

Grid or flexbox?

Rule of thumb: layout of the page or section is grid; alignment inside a component is often flexbox. Plenty of components use both.

Move on when you can build a holy-grail layout (header, sidebar, main, footer) with template areas and a responsive image gallery with minmax.

Key concepts

  • Grid tracks and the fr unit
  • repeat(), minmax() and auto-fill/auto-fit
  • Line-based placement
  • Named template areas
  • Implicit grid and auto rows
  • Subgrid
  • Source order and accessibility

Mini project

Build a dashboard shell with named areas (header, sidebar, main, footer) that rearranges on mobile, and a stats card grid inside main that auto-fits without media queries.

Check yourself

What is the practical difference between auto-fill and auto-fit when there are only two items?

Free resources