CSS

Responsive Header, Sidebar, and Main Content Layout with CSS Grid

Implement a flexible page layout featuring a header, sidebar, and main content area using CSS Grid, responsively adapting from a stacked mobile view to a multi-column desktop layout.

.grid-container {
  display: grid;
  grid-template-columns: 1fr; /* Mobile: single column */
  grid-template-rows: auto auto 1fr; /* Header, Sidebar, Main stacked */
  gap: 10px;
  min-height: 100vh; /* Full viewport height */
  box-sizing: border-box; /* Include padding/border in height */
}

.header {
  grid-column: 1 / -1; /* Spans full width */
  background-color: #d1e7dd; padding: 20px;
}

.sidebar {
  background-color: #f8d7da; padding: 20px;
}

.main-content {
  background-color: #cfe2ff; padding: 20px;
}

@media (min-width: 768px) {
  .grid-container {
    grid-template-columns: 200px 1fr; /* Desktop: Sidebar (200px) + Main (rest) */
    grid-template-rows: auto 1fr; /* Header on top, then Sidebar/Main */
  }
  .header {
    grid-column: 1 / -1; /* Header still spans both columns */
  }
  .sidebar {
    grid-column: 1 / 2;
    grid-row: 2 / 3;
  }
  .main-content {
    grid-column: 2 / 3;
    grid-row: 2 / 3;
  }
}
How it works: This CSS Grid snippet creates a common web layout structure: a header, a sidebar, and a main content area. On mobile screens, items stack vertically using a single column template. For wider screens (768px and above), a media query transforms the layout into a two-column design with a fixed-width sidebar and a fluid main content area, demonstrating responsive grid templating.

Need help integrating this into your project?

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

Hire DigitalCodeLabs