Using grid-template-areas to create complex grid layouts
Using grid-template-areas
is a powerful way to create complex grid layouts. The idea is to define a grid container and then use the grid-template-areas
property to specify the layout of the grid items.
Here is an example
.wrapper {
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-auto-rows: minmax(100px, auto);
grid-template-areas:
"hd hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main main"
"ft ft ft ft ft ft ft ft ft";
}
In this example, we're creating a grid container with 9 columns and automatic row heights. The grid-template-areas
property is used to specify the layout of the grid items.
Each string in the grid-template-areas
property represents a row in the grid. The characters in each string represent the grid areas, separated by spaces. In this case, we have three rows:
The first row has 9 cells, all occupied by the
hd
area (header).The second row has 9 cells, with the first 3 cells occupied by the
sd
area (sidebar) and the remaining 6 cells occupied by themain
area (main content).The third row has 9 cells, all occupied by the
ft
area (footer).
To assign each grid item to its corresponding area, we use the grid-area
property:
.header {
grid-area: hd;
}
.footer {
grid-area: ft;
}
.content {
grid-area: main;
}
.sidebar {
grid-area: sd;
}
Now, let's create the HTML structure:
<div class="wrapper">
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="content">Content</div>
<div class="footer">Footer</div>
</div>
This will create a complex grid layout with a header, sidebar, main content, and footer.
You can also leave grid cells empty by using the full stop character (.
) in the grid-template-areas
property. For example:
.wrapper {
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-auto-rows: minmax(100px, auto);
grid-template-areas:
"hd hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main main"
". . . ft ft ft ft ft ft";
}
In this case, the third row has 3 empty cells, followed by the ft
area (footer).
Making a website responsive is very important because most people use mobiles and tablets to visit websites. We have a simple guide with code examples to help you learn about responsive web design. Click this link to get a free copy.