← Back to all snippets
CSS

Flexible Page Layout with Dynamic Sidebar using CSS Grid Areas

Design a versatile page layout featuring a main content area and a sidebar, easily reconfigurable for different screen sizes by defining and assigning elements to named CSS Grid `grid-template-areas`.

.page-layout {
    display: grid;
    grid-template-columns: 1fr 3fr; /* Sidebar 1/4, Main 3/4 */
    grid-template-rows: auto 1fr auto; /* Header, Main/Sidebar, Footer */
    grid-template-areas:
        "header header"
        "sidebar main"
        "footer footer";
    min-height: 100vh; /* Full viewport height */
}

.header { grid-area: header; background-color: #eee; padding: 10px; }
.sidebar { grid-area: sidebar; background-color: #ddd; padding: 10px; }
.main-content { grid-area: main; background-color: #f9f9f9; padding: 10px; }
.footer { grid-area: footer; background-color: #eee; padding: 10px; }

/* Responsive adjustment: Stack on small screens */
@media (max-width: 768px) {
    .page-layout {
        grid-template-columns: 1fr; /* Single column */
        grid-template-areas:
            "header"
            "sidebar"
            "main"
            "footer";
    }
}
How it works: This CSS establishes a responsive page layout using CSS Grid `grid-template-areas`. Named areas (`header`, `sidebar`, `main`, `footer`) are defined and assigned to grid cells, making the layout's structure visually clear. Media queries then easily reconfigure these areas into a single column for smaller screens, demonstrating a powerful way to handle responsive design without changing the HTML structure. This approach requires an HTML structure with corresponding classes assigned to header, sidebar, main, and footer elements within a `.page-layout` container.

Need help integrating this into your project?

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

Hire DigitalCodeLabs