Grid

Named grid areas

Describe a page layout with readable named regions and assign header, navigation, main, aside, and footer elements to them.

Named areas are my favorite Grid feature. You draw the layout as text, right in the CSS, and then tell each element which word it belongs to. Anyone can read the result.

A classic page with a header, a sidebar, a main column, and a footer:

.page {
  display: grid;
  grid-template-columns: 16rem 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
}

.site-header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: main; }
.site-footer { grid-area: footer; }

Look at grid-template-areas. Each string is a row. Each word is a cell. The header spans both columns because header appears twice on the first row. Then grid-area: header on the element puts it there.

The rules of the map

Three things the browser insists on:

  • every row string must have the same number of cells
  • repeating a name must form a rectangle, an L-shape is invalid
  • a dot (.) marks a cell you want to leave empty

Break one of these and the whole grid-template-areas declaration is invalid. The browser drops it and falls back to auto-placement, which looks like “my layout stopped working” with no error. Check the Styles panel in DevTools: an invalid declaration shows with a warning icon.

Start narrow, then redraw

The real strength shows up with responsive layouts. On a narrow screen you want everything stacked, in document order. Wider, you want the sidebar next to the main content. You only need to redraw the map:

.page {
  grid-template-columns: 1fr;
  grid-template-areas:
    "header"
    "main"
    "sidebar"
    "footer";
}

@media (min-width: 48rem) {
  .page {
    grid-template-columns: minmax(12rem, 1fr) 3fr;
    grid-template-areas:
      "header header"
      "sidebar main"
      "footer footer";
  }
}

Same HTML, same grid-area assignments. Only the picture changes. Notice that on the narrow layout main comes before sidebar, which matches the order I’d want a screen reader to use.

Visual order is not reading order

This is the same warning from the previous lesson, and it matters even more here. Areas move boxes on screen. They do not move anything in the accessibility tree or in the Tab order. The wide layout shows the sidebar first, but the HTML still has the main content first, and that’s the order assistive technology follows.

So write HTML that reads well with no CSS at all. Then paint it with areas.

Try it on your course page: turn on area names in the Grid overlay so you can see the map on the real page. Then break it on purpose. Misspell sidebar in one grid-area, or make the footer an L-shape. Watch how the browser reacts, then fix it. Knowing what the failure looks like saves you an hour later.

Lesson completed