CSS

Responsive Grid Layout with Named Areas

Learn to create flexible and responsive web layouts using CSS Grid's `grid-template-areas` and media queries to adapt design for various screen sizes.

.grid-container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: auto 1fr auto auto;
  grid-template-areas:
    "header"
    "main"
    "sidebar"
    "footer";
  min-height: 100vh;
}

.header { grid-area: header; background-color: #f1f1f1; padding: 20px; text-align: center; }
.main { grid-area: main; background-color: #e0e0e0; padding: 20px; }
.sidebar { grid-area: sidebar; background-color: #d0d0d0; padding: 20px; }
.footer { grid-area: footer; background-color: #f1f1f1; padding: 20px; text-align: center; }

@media (min-width: 768px) {
  .grid-container {
    grid-template-columns: 1fr 3fr;
    grid-template-rows: auto 1fr auto;
    grid-template-areas:
      "header header"
      "sidebar main"
      "footer footer";
  }
}

/* Basic HTML Structure for context:
<div class="grid-container">
  <header class="header">Header</header>
  <main class="main">Main Content</main>
  <aside class="sidebar">Sidebar</aside>
  <footer class="footer">Footer</footer>
</div>
*/
How it works: This snippet demonstrates how to build a responsive page layout using CSS Grid's `grid-template-areas`. It defines named areas like `header`, `main`, `sidebar`, and `footer` for the grid items. On smaller screens, these areas stack vertically. A media query then reconfigures the `grid-template-areas` for wider screens, placing the sidebar next to the main content, creating a common two-column layout. This approach offers a highly readable and maintainable way to design complex responsive layouts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs