grid-template-areas
Describes the grid layout with named areas, almost like a drawing in code.
- Initial value
none- Inherited
- No
- Animatable
- no
- Applies to
- grid containers
- JavaScript
element.style.gridTemplateAreas = '"head head" "side main"'
Example
#.layout {
display: grid;
grid-template-columns: 120px 1fr;
grid-template-areas:
"header header"
"menu content";
gap: 8px;
}
.layout header { grid-area: header; }
.layout nav { grid-area: menu; }
.layout main { grid-area: content; }<div class="layout stage">
<header class="box" style="grid-area: header">CodeWorlds</header>
<nav class="box" style="grid-area: menu">Menu</nav>
<main class="box" style="grid-area: content">Lesson 4: Grid</main>
</div>Definition and usage
#The grid-template-areas property lets you draw the layout with strings. Each string is one row, and the words inside it are cell names. Repeating the same name in neighboring cells merges them into a single area.
You assign items to areas with the grid-area property, for example grid-area: sidebar. A dot (.) marks an empty cell. Areas must be rectangular; an L-shape isn’t allowed.
This is the most readable way to describe a whole page layout. On phones, all it takes is a different drawing inside a @media query, and the items rearrange themselves.
Syntax
#grid-template-areas: none | "<name> <name> …" "<name> …" …;Values
#"head head" "side main" "foot foot"
A full-width header and footer, with a sidebar and content in the middle."head side" "main side" "foot side"
The sidebar takes up the full height on the right side."head head" ". main" "foot foot"
with a dot
The dot leaves an empty cell. The side item has no area of its own, so it ends up in the free cell at the end.
Values in practice
#"head head" "side main" "foot foot"
.demo { grid-template-areas: "head head" "side main" "foot foot"; }"head side" "main side" "foot side"
.demo { grid-template-areas: "head side" "main side" "foot side"; }"head head" ". main" "foot foot"
.demo { grid-template-areas: "head head" ". main" "foot foot"; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Line up the names in columns with spaces. The code then looks like a map of the layout and is easy to read.
- Every row must have the same number of cells, and areas must be rectangular. Otherwise the whole declaration is ignored.
Related entries
#- grid-areaAssigns an item to a named grid area, or sets its rows and columns all at once.
- grid-templateA shorthand that sets the grid’s rows, columns, and named areas in one declaration.
- grid-template-columnsDefines the grid’s columns: their number and widths.
- grid-template-rowsDefines the grid’s rows: their number and heights.
Spotted a mistake or missing an example? Write to us.