CSS

Define a Semantic Full-Page Layout using CSS Grid Areas

Structure complex web page layouts (header, nav, main, aside, footer) easily and semantically using CSS Grid's `grid-template-areas` for clarity, maintenance, and responsiveness.

.grid-container {
  display: grid;
  grid-template-columns: 1fr 3fr; /* Two columns: 1 part for sidebar, 3 parts for main */
  grid-template-rows: auto 1fr auto; /* Three rows: header (auto), main (grows), footer (auto) */
  grid-template-areas:
    "header header"
    "nav    main"
    "footer footer";
  min-height: 100vh;
  gap: 1rem;
  font-family: sans-serif;
}

/* Assign grid areas to elements */
header { grid-area: header; background-color: #0056b3; color: white; padding: 1rem; }
nav    { grid-area: nav;    background-color: #e9ecef; padding: 1rem; }
main   { grid-area: main;   background-color: #f8f9fa; padding: 1rem; }
footer { grid-area: footer; background-color: #343a40; color: white; padding: 1rem; }

/* Example for smaller screens, collapsing nav below header */
@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: 1fr;
    grid-template-areas:
      "header"
      "nav"
      "main"
      "footer";
  }
}
How it works: This snippet demonstrates a powerful way to define full-page layouts using CSS Grid `grid-template-areas`. You visually name sections of your layout (`header`, `nav`, `main`, `footer`) within `grid-template-areas`. Then, each HTML element is assigned its corresponding `grid-area`. This approach makes the layout highly readable and easy to modify, especially when combined with media queries to create different layouts for various screen sizes, as shown with the mobile example.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs