In this article, I want to share two responsive techniques that I learned from Wes Bos’ CSS Grid Tutorial. Thanks, Wes!
Template Areas
You can make a site responsive simply by changing the template areas with a media query.
In this example, let’s imagine a regular page where on desktop the main and aside are side by side, and on mobile, they stack on top of each other. The header, nav and footer always span across the entire page.
<div class="grid">
<header>Header</header>
<nav>Nav</nav>
<main>Main Content</main>
<aside>Sidebar</aside>
<footer>Footer</footer>
</div>
Here’s the mobile first CSS that would accomplish that just by reconfiguring the template areas. No need to modify the main or aside themselves:
.grid {
display: grid;
grid-template-columns: 1fr;
grid-template-areas: "hr"
"nv"
"mn"
"sb"
"ft";
}
header { grid-area: hr; }
nav { grid-area: nv; }
main { grid-area: mn; }
aside { grid-area: sb; }
footer { grid-area: ft; }
@media (min-width: 767px) {
.grid {
grid-template-columns: 2fr 1fr;
grid-template-areas: "hr hr"
"nv nv"
"mn sb"
"ft ft";
}
}
Responsive Equal Width Elements
It’s common to have a series of elements (pictures, products, cards, rectangles of some sort) in a grid. You may want to show 4 or 5 per row, but as the screen gets smaller, show fewer, until you only see one per row.
<div class="grid">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
<div class="item">Item 8</div>
<div class="item">Item 9</div>
<div class="item">Item 10</div>
</div>
You don’t even need a media query for this one:
.grid {
display: grid;
grid-gap: 20px;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}
Rachel Andrew wrote an article more in-depth about using minmax and autofill.
Further Reading
Check out Wes Bos’ tutorial, anything by Rachel Andrew, or Mozilla’s web docs.