Template Areas
In our previous example, we learned how to create a basic layout by positioning items with grid lines. Another method for positioning items is to use named grid areas with the grid-template-areas
and grid-area
properties. The best way to explain this is with an example. Let's recreate the grid from our previous example with the grid-template-areas property:
.container {
display: grid;
width: 100%;
height: 600px;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: 80px 1fr 1fr 100px;
grid-gap: 1rem;
grid-template-areas:
"header header header"
"sidebar content-1 content-1"
"sidebar content-2 content-3"
"footer footer footer";
}
Here we have defined three columns and four rows. Instead of placing each individual item, we can define the entire layout using the grid-template-areas
property. We can then assign those areas to each grid item using the grid-area
property.
Our HTML:
<div class="container">
<div class="header">header</div>
<div class="sidebar">sidebar</div>
<div class="content-1">Content-1</div>
<div class="content-2">Content-2</div>
<div class="content-3">Content-3</div>
<div class="footer">footer</div>
</div>
The rest of our CSS:
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.content-1 {
grid-area: content-1;
}
.content-2 {
grid-area: content-2;
}
.content-3 {
grid-area: content-3;
}
.footer {
grid-area: footer;
}
Here is the result: