Grid and Responsive Design
Two-dimensional layouts, media queries and mobile-first CSS.
What you will learn
- Build a grid layout
- Write media queries
- Use clamp and custom properties
CSS Grid lays out content in rows and columns at the same time. Use Flexbox for one-dimensional alignment and Grid for whole-page or gallery layouts. Combined with media queries, it lets one page adapt to any screen.
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr); /* three equal columns */
gap: 1rem;
}The fr unit means a fraction of the free space. 1fr 2fr creates a column twice as wide as the first.
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 1rem;
}This fits as many columns of at least 220px as the container allows, and grows them evenly. Resize the window and columns appear or disappear by themselves.
.page {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }Mobile-first responsive design
Write styles for the smallest screen first, then use min-width media queries to enhance for larger ones. The result is simpler CSS, and phones download less.
.page { display: block; } /* phone: everything stacked */
@media (min-width: 768px) {
.page {
display: grid;
grid-template-columns: 220px 1fr; /* tablet and up */
}
}h1 { font-size: clamp(1.75rem, 4vw, 3rem); } /* min, preferred, max */
.container { width: min(100% - 2rem, 1100px); margin-inline: auto; }img { max-width: 100%; height: auto; display: block; }:root { --bg: #fff; --text: #111; }
@media (prefers-color-scheme: dark) {
:root { --bg: #0b0b0b; --text: #eaeaea; }
}
body { background: var(--bg); color: var(--text); }Use your browser's device toolbar to try phone widths. Do not design only for your own screen.
Try it yourself
Make a three-column card gallery that collapses to two columns under 900px and one column under 600px, using media queries with max-width.
Show solution
.gallery { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; }
@media (max-width: 900px) { .gallery { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 600px) { .gallery { grid-template-columns: 1fr; } }