Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a page layout with grid

Short answer

Name the areas in grid-template-areas and place the elements into them with grid-area:

<style>
  .page { display: grid; gap: 6px; grid-template-columns: 90px 1fr 90px; grid-template-rows: auto 1fr auto; min-height: 220px;
    grid-template-areas: "head head head" "nav main ads" "foot foot foot"; }
  .page > * { padding: 8px; background: lavender; }
  header { grid-area: head; } nav { grid-area: nav; } main { grid-area: main; background: whitesmoke; }
  aside { grid-area: ads; } footer { grid-area: foot; }
</style>
 
<div class="page">
  <header>Header</header><nav>Menu</nav><main>Content</main><aside>Ads</aside><footer>Footer</footer>
</div>

Each quoted string is a grid row and each word is a cell. Repeating a name stretches the area over several cells.

On a phone

The main benefit of areas is changing the layout without touching the HTML. For a narrow screen you just rewrite the map as one column:

@media (max-width: 600px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas: "head" "nav" "main" "ads" "foot";
  }
}

Common mistake

The map must be rectangular: every row has the same number of cells, and each area is a solid rectangle. If you write, say, "head head" "nav main ads", the browser treats the whole rule as invalid and silently ignores it. Mark an empty cell with a dot.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.