How To Use Css Grid And Name Layout Areas With Grid-Template-Areas
CSS Grid is a two-dimensional layout system. It controls rows and columns at the same time. Apply display: grid to the parent, define the tracks, and place the children. The most readable way to build a full page layout is to give each section a name with grid-template-areas.
Basic columns
css">.lotgrafix-grid {
display: grid;
grid-template-columns: repeat( 3, 1fr );
gap: 20px;
}
The fr unit means a fraction of the available space. Three 1fr columns are three equal columns.
Responsive grid without media queries
.lotgrafix-grid {
display: grid;
grid-template-columns: repeat( auto-fit, minmax( 250px, 1fr ) );
gap: 20px;
}
Columns are never narrower than 250px and the grid adds or removes columns automatically as the screen changes.
Step 1: name each section with grid-area
Give every section of the layout a name. The name can be anything you want.
.lotgrafix-header { grid-area: header; }
.lotgrafix-sidebar { grid-area: sidebar; }
.lotgrafix-main { grid-area: main; }
.lotgrafix-footer { grid-area: footer; }
Step 2: draw the layout with grid-template-areas
Each quoted string is a row and each word is a column cell. Repeating a name makes that section span several cells.
.lotgrafix-layout {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
gap: 20px;
}
HTML
<div class="lotgrafix-layout">
<header class="lotgrafix-header">Header</header>
<aside class="lotgrafix-sidebar">Sidebar</aside>
<main class="lotgrafix-main">Content</main>
<footer class="lotgrafix-footer">Footer</footer>
</div>
Step 3: redefine the areas for mobile
This is where named areas shine. To change the layout on small screens you only redraw the map. The HTML and the grid-area rules stay the same.
@media ( max-width: 768px ) {
.lotgrafix-layout {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
}
}
Empty cells
Use a dot to leave a cell empty.
grid-template-areas:
"header header header"
"sidebar main ."
"footer footer footer";
Useful alignment properties
justify-items: aligns items horizontally inside their cell.align-items: aligns items vertically inside their cell.place-items: shorthand for both. Example:place-items: center.justify-contentandalign-content: align the whole grid inside its container.grid-columnandgrid-row: place or span an item by line numbers. Example:grid-column: 1 / -1spans all columns.


