CSS Grid areas
Let’s say you want to build a layout like the one below using CSS Grid. You have two choices, an insane way, and a sane way.

The insane way
This method will almost always tip you into the insane spectrum while creating, modifying, or using the grid. I’m not going to show you the method. But, I tell you this, it involves imaginary lines, properties like grid-row
and grid-column
, and some /
s.
The sane way
The sane way utilises the CSS property grid-template-areas
.
CSS
.the-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 64px 1fr 64px;
grid-template-areas:
"header header header header"
"sidebar content content content"
"footer footer footer footer";
}
.the-header {
grid-area: header;
}
.the-sidebar {
grid-area: sidebar;
}
.the-content {
grid-area: content;
}
.the-footer {
grid-area: footer;
}
/* Presentational styles */
.the-page {
min-height: 480px;
display: grid;
place-items: center;
}
.the-grid {
min-height: 400px;
min-width: 300px;
gap: 0.25em;
}
.the-header,
.the-sidebar,
.the-content,
.the-footer {
--rgb: 0,0,0;
--opacity: 1;
--bg-opacity: 0.2;
padding: 1em;
border: 1px solid;
color: rgba(var(--rgb),var(--opacity));
background-color: rgba(var(--rgb),var(--bg-opacity));
}
.the-header {
--rgb: 0,122,255;
}
.the-sidebar {
--rgb: 155,155,155;
}
.the-footer {
--rgb: 246,83,83;
}
HTML
<div class="the-page">
<div class="the-grid">
<div class="the-header">Header</div>
<div class="the-sidebar">Sidebar</div>
<div class="the-content">Content</div>
<div class="the-footer">Footer</div>
</div>
</div>
Preview
Let me take you line by line. Let’s look at the class .the-grid
.
display: grid
: sets the element as block element and layout for its children to be grid.grid-template-columns: repeat(4, 1fr)
: The valuerepeat(4, 1fr)
is equivalent to1fr 1fr 1fr 1fr
. This property tells the browser to have a grid layout of four columns of1fr
. If you want to learn more about thefr
unit, CSS-Tricks have a good article.grid-template-rows: 64px 1fr 64px
: tells the browser to have the grid to three rows,64px
,1fr
, and64px
height respectively.grid-template-areas
. Here each quoted text corresponds to each row. Take a look at the first row,"header header header header"
, it tells the browser to treat all four columns in the first row as areaheader
. For the second row,"sidebar content content content"
treat the first column assidebar
and the rest of the three columns as areacontent
. It’s important that the number of area names in each row should match the number of columns in that row.
grid-template-areas:
"header header header header"
"sidebar content content content"
"footer footer footer footer";
Now, let’s place the child elements on the grid. Look at the first child element .the-header
. The property grid-area: header;
(no need of quotes when specifying area) tells the browser to use area header
. Similarly, other children are placed in their corresponding areas.