Page Layout with Areas
A grid is also great for the layout of a whole page. Our page has four parts: the header (header), the menu (nav), the main content (main) and the footer (footer). Let's put the menu on the left next to the content, the header above them and the footer below them, both across the whole width.
We could place each part with the numbers of the grid lines, but there's a clearer way: we can give parts of the grid names and draw the layout in CSS. The value of the grid-template-areas property has one string (a text in quotes) for each row of the grid. In the string, we write a name for each column of that row. Neighboring cells with the same name together form one area.
body {
display: grid;
grid-template-columns: 8rem 1fr;
grid-template-areas:
"header header"
"menu content"
"footer footer";
}This grid has two columns and three rows. The header area takes up both columns of the first row, menu and content share the second row, and footer takes up the whole last row. The menu column is 8rem wide and the content gets the rest. We make up the names of the areas ourselves; they don't have to match the names of the elements. Each name is one word without spaces.
Then, with the grid-area property, we tell each element which area it belongs to. Here, the name is written without quotes:
nav {
grid-area: menu;
}Two things to keep in mind: all the strings must have the same number of names, and each area must be a rectangle. Otherwise, the browser ignores the whole declaration. A cell that should stay empty is written as a dot (.).
Instructions
In the rule for body, add the declarations display: grid and grid-template-columns: 8rem 1fr. For now, the four parts of the page fill the cells one after another, which isn't what we want yet.
In the same rule, add the grid-template-areas property with the three rows from the example above: "header header", "menu content" and "footer footer". Nothing changes yet: the plan is drawn, but the elements don't know where they belong.
Put the elements into the areas: in the rule for header, add the declaration grid-area: header; in the rule for nav, grid-area: menu; in the rule for main, grid-area: content; and in the rule for footer, grid-area: footer.
Start programming for free
5/7