This is intro to CSS grid layout part 5. So far we have taken a look at following topics. It is recommended to take a look if you are not familiar with css grid layout basics.
In this post, I will focus on explaining how to use grid area with area names for positioning grid items with an example. Let’s take a look it.
Example

We have a layout of multiple items. Note that the header is not spanning to the end but the last slot is empty.
HTML Code
This is the html code used for the example
<div class="challenge"> <div class="header">Header</div> <div class="small-box-1">Small box</div> <div class="small-box-2">Small box</div> <div class="small-box-3">Small box</div> <div class="main-content">Main content</div> <div class="sidebar">Sidebar</div> <div class="footer">Footer</div> </div>
CSS Code
We have 4 rows and 4 columns which make 16 unit areas. To use area based positioning, you need to define each unit area with an area name. You can decide the name as you prefer. As you can see, grid-template-areas property is defined with 16 names. For example, head is located at the first row and spanning from first to third column. “.” represents an empty slot. After you define the area representation, all you need to do is to specify the area name for each class. Take a look at line 21 and others.
.challenge { width: 1000px; margin: 30px auto; display: grid; grid-template-rows: 100px 200px 400px 100px; grid-template-columns: repeat(3, 1fr) 200px; grid-gap: 35px; grid-template-areas: "head head head ." "small-box-1 small-box-2 small-box-3 side" "main main main side" "foot foot foot foot"; & > * { background-color: orangered; padding: 15px; color: white; font-size: 30px; font-family: sans-serif; } .header { grid-area: head; } .small-box-1 { grid-area: small-box-1; } .small-box-2 { grid-area: small-box-2; } .small-box-3 { grid-area: small-box-3; } .sidebar { grid-area: side; } .main-content { grid-area: main; } .footer { grid-area: foot; } }
It is very important to note that you have to have a complete area representation. Since you have 16 unit slots (4 rows * 4 columns), you have to have 16 area names in order to use it. It is fairly simple to use for a simple area layout. However, if you have a complex layout, it could be inconvenient to use it. i.e., 10 rows and 10 columns. In such a case, it would be better to use grid lines instead of names.