CSS · Course navigation

CSS Grid Layout

Build a two-dimensional page layout with named areas and a responsive card grid.

On this page

The concept

Grid lays out items in rows and columns at once. grid-template-columns defines the columns, with the fr unit sharing the free space. grid-template-areas names regions in a drawing-like way, and grid-area places an element in a region. For a gallery, repeat(auto-fit, minmax(10rem, 1fr)) creates as many columns of at least 10rem as fit, so the grid reflows without media queries. Use Grid for page layout and two-dimensional arrangements, and flexbox for a single row or column of items.

Code example

CSS
.layout {
  display: grid;
  grid-template-columns: 12rem 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  gap: 1rem;
}
.layout > header { grid-area: header; }
.layout > nav { grid-area: sidebar; }
.layout > main { grid-area: main; }
.layout > footer { grid-area: footer; }

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
  gap: 0.5rem;
}

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1.layout {
2 display: grid;
3 grid-template-columns: 12rem 1fr;
4 grid-template-areas:
5 "header header"
6 "sidebar main"
7 "footer footer";
8 gap: 1rem;
9}
10.layout > header { grid-area: header; }
11.layout > nav { grid-area: sidebar; }
12.layout > main { grid-area: main; }
13.layout > footer { grid-area: footer; }
14
15.gallery {
16 display: grid;
17 grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
18 gap: 0.5rem;
19}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
The element becomes a grid container and its children become grid items.—
—
A fixed 12rem sidebar column and one flexible column that takes the rest.—
—
The header spans both columns. Each quoted string is a row, and each word names a cell.—
—
The second row has the sidebar on the left and the main content on the right.—
—
Place the header element in the area named header.—
—
As many columns as fit, each at least 10rem wide, sharing any extra space equally.—
—

Behind the scenes

How CSS processes this code

The browser matches selectors, computes styles, and paints the result. CSS does not produce console output.