CSS
Responsive Grid Layout Reordering with grid-template-areas
Adapt content order and placement dynamically across different screen sizes using CSS Grid's `grid-template-areas` for flexible mobile-first or desktop-first designs.
/* CSS */
.page-layout {
display: grid;
gap: 1rem;
padding: 1rem;
background-color: #f0f0f0;
}
/* Define grid areas for mobile (stacked layout) */
.page-layout {
grid-template-areas:
"header"
"sidebar"
"main"
"footer";
}
/* Assign items to named areas */
.header { grid-area: header; background-color: #a7d9ee; padding: 1rem; }
.sidebar { grid-area: sidebar; background-color: #d1f4d9; padding: 1rem; }
.main { grid-area: main; background-color: #fff9c4; padding: 1rem; }
.footer { grid-area: footer; background-color: #ffccbc; padding: 1rem; }
/* Media query for larger screens (e.g., tablet and desktop) */
@media (min-width: 768px) {
.page-layout {
grid-template-columns: 1fr 3fr; /* Two columns: 1 part for sidebar, 3 for main */
grid-template-rows: auto 1fr auto; /* Header, main/sidebar, footer */
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
}
/* HTML */
<div class="page-layout">
<header class="header"><h1>Page Header</h1></header>
<aside class="sidebar"><h2>Sidebar Content</h2></aside>
<main class="main"><p>Main content area. This will be below the sidebar on mobile and next to it on desktop.</p></main>
<footer class="footer"><p>Page Footer</p></footer>
</div>
How it works: This snippet demonstrates responsive layout reordering using CSS Grid's `grid-template-areas`. It defines named areas (`header`, `sidebar`, `main`, `footer`) and assigns each child element to its corresponding area using `grid-area`. For mobile, the `grid-template-areas` stacks them vertically. For wider screens (via media query), the `grid-template-columns` and `grid-template-rows` are redefined, and a new `grid-template-areas` layout places the sidebar next to the main content, achieving a completely different visual arrangement without changing the HTML structure. This offers powerful control over content flow across breakpoints.