Sub topic 2
Mobile-First CSS with `min-width`
Assume you know basic HTML and CSS, including selectors, the box model, and rem, percentages, and pixels. A mobile-first layout starts with the narrowest useful layout. Larger layouts then add changes with min-width media queries.
Start with the smallest layout
The viewport is the visible area of a page. CSS pixels are the units the browser uses to lay out that area. The viewport meta tag makes the CSS viewport match the device width on mobile browsers.
<!doctype html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.layout {
display: grid;
gap: 1rem;
padding: 1rem;
}
@media (min-width: 48em) {
.layout {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 80em) {
.layout {
grid-template-columns: 2fr 1fr 1fr;
max-width: 80rem;
margin-inline: auto;
}
}
</style>
</head>
<body>
<main class="layout">
<article>Main content</article>
<aside>Related content</aside>
<aside>Resources</aside>
</main>
</body>
</html>The base rule creates one column. At 48em, the layout gains two equal columns. At 80em, it gains three columns and a maximum width. min-width means the rule applies at that width and every wider width.
Map CSS to design frames
Create mobile, tablet, and desktop frames in your design tool using the same breakpoint values as the CSS. The exact frame widths can be representative. The important part is that each frame demonstrates the behavior at that range.
Choose breakpoints from content
Resize the page continuously and watch for failure points:
- Add a breakpoint when navigation wraps or becomes crowded.
- Add a breakpoint when a readable text measure becomes too narrow or too wide.
- Keep a fluid layout between breakpoints with flexible tracks and relative units.
- Record chosen values as design tokens so design frames and CSS remain aligned.
| Token | Value | Use |
|---|---|---|
| `--bp-tablet` | `48em` | Two-column layout |
| `--bp-desktop` | `80em` | Wide grid and centered content |
Adapt layout patterns
Stack related content on mobile. Use columns when each item has enough room. Use repeat(auto-fit, minmax(...)) for cards that can add or remove columns fluidly without another breakpoint.
Exercise
Why should a mobile-first stylesheet place the one-column rule outside a media query?
Show answer
It makes the narrow layout the default, while wider layouts add only the changes needed at their min-width breakpoints.