Responsive Design
Most of the bakery's visitors check the opening hours on a phone while walking past. A few order a birthday cake from a laptop at work. The page must work on a 360-pixel phone and a 1,440-pixel monitor without building two sites. Responsive design is the habit of letting one page adapt.
The rule
Start small, use flexible units, and add media queries only where the layout breaks.
1. Let the page know the real width. The viewport meta tag from the HTML section is the foundation. Without it, phones render as if they were desktops and everything else in this lesson is wasted.
2. Flexible units. Fixed pixels do not stretch; relative units do:
| Unit | Relative to |
|---|---|
% |
the parent's size |
rem |
the root font size (16 pixels by default), so 1.5rem is 24 pixels |
em |
the element's own font size |
vw, vh |
1% of the viewport's width or height |
Using rem for text and spacing also respects visitors who raise their browser's default font size.
3. Fluid media. One line stops big photos from overflowing narrow screens:
img {
max-width: 100%;
height: auto;
}4. Media queries, mobile first. Write the base styles for small screens, then add rules for larger ones with min-width:
.menu {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
@media (min-width: 40rem) {
.menu { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 64rem) {
.menu { grid-template-columns: repeat(3, 1fr); }
}Read min-width: 40rem as "from 640 pixels and up". Phones get one column, tablets two, laptops three.
Choose these breakpoints by watching your own content: widen the browser until the design starts to look wrong, and add a query there. Chasing the exact widths of popular devices is a losing game, since new sizes appear every year.