Categories
CSS Web development

CSS grid-template-areas Property

CSS grid-template-areas Property

The CSS grid-template-areas property defines areas within the grid layout.

You can name grid items by using the CSS grid-area property, and then reference to the name in the CSS grid-template-areas property.

Syntax:

grid-template-areas: none|itemnames;

none (default) – no named grid areas.

itemnames – a sequence that defines how each columns and row should display.

Example1:

<!DOCTYPE html>
<html>
<head>
<style>
.item1 {
  grid-area: exampleArea;
}

.grid-container {
  display: grid;
  grid-template-areas: 'exampleArea exampleArea . . .';
  grid-gap: 10px;
  background-color: #e9c46a;
  padding: 10px;
}

.grid-container > div {
  background-color: #f4a261;
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
</style>
</head>
<body>

<div class="grid-container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>  
  <div class="item4">4</div>
  <div class="item5">5</div>
  <div class="item6">6</div>
  <div class="item7">7</div>
  <div class="item8">8</div>
  <div class="item9">9</div>
</div>

</body>
</html>

Output:

1
2
3
4
5
6
7
8
9

Example2:

Name all items, and make a ready-to-use webpage template:

<!DOCTYPE html>
<html>
<head>
<style>
.item-1 { grid-area: header; }
.item-2 { grid-area: menu; }
.item-3 { grid-area: main; }
.item-4 { grid-area: side; }
.item-5 { grid-area: footer; }

.grid-container2 {
  display: grid;
  grid-template-areas:
  'header header header header header header'
  'menu main main main side side'
  'menu footer footer footer footer footer';
  grid-gap: 10px;
  background-color: #e9c46a;
  padding: 10px;
}

.grid-container2 > div {
  background-color: #f4a261;
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
</style>
</head>
<body>

<div class="grid-container2">
  <div class="item-1">Header</div>
  <div class="item-2">Menu</div>
  <div class="item-3">Main</div>  
  <div class="item-4">Side</div>
  <div class="item-5">Footer</div>
</div>

</body>
</html>

Output:

Header
Menu
Main
Side
Footer

Enjoy coding!