CSS
Dynamic Responsive Layout with CSS Grid Areas
Create flexible, responsive layouts using `grid-template-areas` for distinct sections that reorder and adapt seamlessly across different screen sizes.
.dashboard-layout {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 20px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh; /* Ensure it takes full viewport height */
}
.header { grid-area: header; background-color: lightblue; padding: 15px; }
.sidebar { grid-area: sidebar; background-color: lightgreen; padding: 15px; }
.main-content { grid-area: main; background-color: lightcoral; padding: 15px; }
.footer { grid-area: footer; background-color: lightgray; padding: 15px; }
@media (max-width: 768px) {
.dashboard-layout {
grid-template-columns: 1fr; /* Single column on small screens */
grid-template-areas:
"header"
"main"
"sidebar" /* Sidebar moves below main content */
"footer";
}
}
How it works: This snippet demonstrates creating a dynamic, responsive page layout using CSS Grid's `grid-template-areas`. Named areas (`header`, `sidebar`, `main`, `footer`) are defined and assigned to specific grid cells. Crucially, a media query is used to redefine `grid-template-areas` for smaller screens, effectively reordering the layout elements (e.g., moving the sidebar below the main content) without altering the HTML structure. This allows for highly adaptable designs that prioritize content flow based on available screen space.