grid-template-areas layout in CSS
23 Naming the areas of a grid
fairLay out a small page with grid-template-areas, so the stylesheet contains a picture of the layout and the markup order stays sensible.
Stuck? Three hints, smallest first
- 1. Each string in
grid-template-areasis one row, and each name in it is one cell. - 2. A name repeated across adjacent cells makes that item span them.
- 3. A
.means an empty cell. Every row must have the same number of cells or the whole declaration is invalid.
<div class="page">
<header class="ph">Header</header>
<nav class="pn" aria-label="Sections">Nav</nav>
<main class="pm">Main</main>
<footer class="pf">Footer</footer>
</div>
.page {
display: grid;
grid-template-areas:
'head head'
'nav main'
'foot foot';
grid-template-columns: 90px 1fr;
grid-template-rows: auto 1fr auto;
gap: 8px;
min-height: 170px;
}
.ph { grid-area: head; }
.pn { grid-area: nav; }
.pm { grid-area: main; }
.pf { grid-area: foot; }
.page > * {
padding: 10px;
border-radius: 6px;
background: #eef1fd;
border: 1px solid #3055d8;
font-size: 0.82rem;
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// Every row of the template must declare the same number of cells, or the
// browser throws the whole declaration away.
const rows = [...css.matchAll(/'([a-z. ]+)'/g)].map((m) => m[1].trim().split(/\s+/));
const widths = [...new Set(rows.map((r) => r.length))];
test('three rows in the template', rows.length, 3);
test('each declares two cells', widths, [2]);
test('the header name is repeated, so it spans both columns', rows[0], ['head', 'head']);
test('and so is the footer', rows[2], ['foot', 'foot']);
test('the middle row splits into nav and main', rows[1], ['nav', 'main']);
test('every area name is claimed by an element', ['head', 'nav', 'main', 'foot'].every((a) => new RegExp('grid-area:\\s*' + a + ';').test(css)), true);
test('the columns are sized as a sidebar plus the rest', /grid-template-columns:\s*90px 1fr/.test(css), true);
test('semantic landmarks, not four divs', ['header', 'nav', 'main', 'footer'].every((t) => hasTag(html, t)), true);
Output
The check that matters is the second: a grid-template-areas whose rows have different cell counts is invalid and the browser discards the whole declaration, so the layout collapses to a single column with no error anywhere. Counting the cells per row is the first thing to do when that happens. The payoff for getting it right is that the stylesheet reads as a diagram, and reordering the layout does not mean reordering the markup — which matters because the markup order is the order a screen reader and the tab key follow.