CSS
Building Responsive Layouts with CSS Grid Areas
Learn how to create complex, responsive page layouts using CSS Grid's `grid-template-areas` for semantic and maintainable code across different screen sizes.
.grid-container {
display: grid;
grid-template-columns: 1fr; /* Single column for small screens */
grid-template-rows: auto;
grid-template-areas:
"header"
"nav"
"main"
"sidebar"
"footer";
gap: 15px;
}
@media (min-width: 768px) {
.grid-container {
grid-template-columns: 200px 1fr; /* Sidebar on left, main content */
grid-template-areas:
"header header"
"nav nav"
"sidebar main"
"footer footer";
}
}
@media (min-width: 1024px) {
.grid-container {
grid-template-columns: 200px 1fr 200px; /* Left sidebar, main, right sidebar */
grid-template-areas:
"header header header"
"nav nav nav"
"sidebar main ad" /* Assuming "ad" for a right sidebar */
"footer footer footer";
}
}
/* Assign grid areas to elements */
header { grid-area: header; }
nav { grid-area: nav; }
main { grid-area: main; }
aside { grid-area: sidebar; }
.ad-slot { grid-area: ad; } /* Example for a right sidebar/ad slot */
footer { grid-area: footer; }
How it works: This snippet demonstrates how to use CSS Grid's `grid-template-areas` to design responsive page layouts. By naming specific areas within your grid container, you can then assign individual grid items to these areas. Media queries are used to redefine the `grid-template-areas` property, allowing the layout to adapt gracefully to different screen sizes without altering the HTML structure, leading to cleaner and more maintainable CSS.