Mobile-First with Fluid Sizing, Media and Container Queries
Write styles that start from the smallest screen and layer up, keep type fluid with clamp(), and switch layouts with media and container queries.
Contentsand lesson path
On this page
- Why it matters
- Start small, layer up
- Fluid type with clamp(), and a media query
- Container queries: components that fit their slot
- Zoom: can fluid text still double?
- Check your understanding
- Apply it
- Review prompt
Lessons of Responsive Layout with Flexbox & Grid
- Flexbox for Rows, Columns and Alignment Worked example · 25 min
- Grid for Pages and Card Collections Worked example · 25 min
- Mobile-First with Fluid Sizing, Media and Container Queries Concept · 25 min
- Serving the Right Image with srcset and sizes Concept · 15 min
- Lab: A Product Listing Page Without a Framework Lab · 30 min
- Check: Layout Challenges at Three Viewports Knowledge check · 8 questions
What you will learn
- Adapt layout and type mobile-first with fluid sizing (clamp()), media queries, container queries and responsive images (srcset and sizes), checking Baseline support before using a feature.
Prerequisites: CSS Cascade & Box Model
01. Why it matters
A layout has to survive an enormous range of widths: a 320px phone, a 768px tablet, a 1280px laptop, a window that the reader resized to half the screen. Flexbox and grid from the previous lessons do most of the mechanical work, but three further tools decide when and how much a layout changes: fluid sizing, which stretches smoothly between limits; media queries, which change styles at viewport widths you choose; and container queries, which change the styles of a component based on the width of the box it sits in.
This lesson builds one small page with all three and measures it, so you can see each tool working and check its browser support before you rely on it.
02. Start small, layer up
Mobile-first means the base stylesheet describes the narrow case, and wider layouts are added with min-width media queries. The order matters more than it looks. The narrow case is the most constrained, so its rules are the ones almost every element needs; wider styles then only add space and columns. Writing desktop-first instead means fighting the base stylesheet with max-width overrides, and each override is another rule that must be true for phones too.
Breakpoints belong in em units, not px. A media query in em is measured against the reader's default font size, so when someone raises it from 16px to 20px, the breakpoint moves out to where the larger text actually needs a new layout. A px breakpoint ignores that setting and changes the layout at the wrong moment.
Choose breakpoints from the content, not from a list of devices: widen the window until the layout looks wrong, then fix it there. Two or three honest breakpoints beat six copied ones.
03. Fluid type with clamp(), and a media query
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fluid layouts</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1 class="fluid">Fresh stock, every morning</h1>
<nav class="nav" aria-label="Primary">
<a href="#catalogue">Catalogue</a>
<a href="#orders">Orders</a>
<a href="#account">Account</a>
</nav>
<p class="rail-note">Product card inside a 300px rail:</p>
<div class="rail">
<article class="card">
<h2>Camera strap</h2>
<p>Woven cotton, two colours.</p>
</article>
</div>
<p class="wide-note">The same card inside a wide column:</p>
<div class="wide">
<article class="card">
<h2>Camera strap</h2>
<p>Woven cotton, two colours.</p>
</article>
</div>
</body>
</html>* {
box-sizing: border-box;
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
padding: 16px;
}
.fluid {
font-size: clamp(1.75rem, 1.2rem + 2.2vw, 3rem);
}
.nav {
display: flex;
flex-direction: column;
gap: 8px;
}
@media (min-width: 48em) {
.nav {
flex-direction: row;
}
}clamp(min, preferred, max) uses the middle value while it stays between the bounds, so type scales with the viewport without a single breakpoint. Measured heading sizes in headless Chromium (via Playwright 1.64.1): 28px at a 320px viewport, 36.096px at 768px, 47.36px at 1280px.
The numbers show each part of the function at work. At 320px the preferred value would be 19.2px + 7.04px = 26.24px, but the 1.75rem minimum wins and the heading stays at 28px. At 768px the preferred value, 19.2px + 16.896px, is inside the bounds. At 1280px it reaches 47.36px, just under the 48px ceiling.
Keeping rem inside the middle term is deliberate. vw tracks only the viewport, but rem also tracks the reader's chosen default font size, so the preferred value grows a little for people who have raised it. A pure vw headline ignores that setting entirely, an accessibility slip the layout checks in this skill look for.
The nav starts as a column in the base stylesheet and becomes a row from 48em up. Measured: at a 700px viewport the nav still computes flex-direction: column; at 800px it computes row. The threshold is 48 × 16px = 768px, exactly the reader's default font size speaking through the em unit.
Use media queries for changes that depend on the window: page shells, navigation shape, showing or hiding chrome. That is the boundary to keep in mind for the next section, because components have a different master.
04. Container queries: components that fit their slot
.rail {
container-type: inline-size;
width: 300px;
}
.wide {
container-type: inline-size;
width: min(720px, 100%);
}
.card {
border: 1px solid #666;
border-radius: 8px;
padding: 12px;
}
.card > * {
margin: 0;
}
@container (min-width: 480px) {
.card {
display: grid;
grid-template-columns: 96px 1fr;
}
}The same .card markup appears twice, once in a 300px rail and once in a wide column, and the two copies end up in different layouts. Measured at one 900px viewport: the card in the rail reports not a grid, staying stacked; the card in the wide container computes 96px 598px, image column beside text.
A media query cannot do this. Both placements share the same viewport, so any @media rule would match both. A container query instead tests the nearest ancestor that declares container-type: inline-size, so the component responds to the space it actually got. The declaration goes on a wrapper: a container query styles the descendants of the container, never the container itself, so the card cannot measure itself.
Before you lean on any newer platform feature, check its Baseline status, the browser vendors' shared signal at web.dev/baseline: "Newly available" means it just landed everywhere, "Widely available" means it has been everywhere long enough to trust for most audiences. Media queries, clamp() and flexbox are long since Widely available; size container queries became Newly available in February 2023 and Widely available in August 2025.
One script produced every measured number in this lesson so far:
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(pathToFileURL('index.html').href);
for (const width of [320, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
const size = await page.$eval('.fluid', (el) => getComputedStyle(el).fontSize);
console.log(`${width}px heading: ${size}`);
}
for (const width of [700, 800]) {
await page.setViewportSize({ width, height: 900 });
const dir = await page.$eval('.nav', (el) => getComputedStyle(el).flexDirection);
console.log(`${width}px nav direction: ${dir}`);
}
await page.setViewportSize({ width: 900, height: 900 });
const cardMode = (sel) =>
page.$eval(sel, (el) => {
const style = getComputedStyle(el);
return style.display === 'grid' ? style.gridTemplateColumns : 'not a grid';
});
const railW = await page.$eval('.rail', (el) => el.clientWidth);
const wideW = await page.$eval('.wide', (el) => el.clientWidth);
const inRail = await cardMode('.rail .card');
const inWide = await cardMode('.wide .card');
console.log(`rail container ${railW}px: card tracks ${inRail}`);
console.log(`wide container ${wideW}px: card tracks ${inWide}`);
await browser.close();320px heading: 28px
768px heading: 36.096px
1280px heading: 47.36px
700px nav direction: column
800px nav direction: row
rail container 300px: card tracks not a grid
wide container 720px: card tracks 96px 598px05. Zoom: can fluid text still double?
Browser zoom (Ctrl and + on Windows and Linux, Cmd and + on macOS) is the other way readers enlarge text, and it treats vw very differently from rem. At 200% zoom a 1rem paragraph is still 16 CSS px, but every CSS pixel is drawn with two device pixels, so the text looks twice as large. What zoom shrinks is the viewport: a 1280px-wide window at 200% zoom has room for only 640 CSS px, so 1vw falls from 12.8px to 6.4px.
Work it through with this lesson's heading. At 100% zoom in that window the preferred value is 19.2px + 2.2 × 12.8px = 47.36px. At 200% zoom it is 19.2px + 2.2 × 6.4px = 33.28 CSS px, drawn as 66.56 device px. Body text doubles from 16 to 32 device px, but the heading grows only 66.56 / 47.36 = 1.41 times. The rem part doubled on screen; the vw part, 28.16 device px both times, did not grow at all.
Playwright cannot press the zoom keys of a real window, but it can reproduce what zoom does to CSS: a viewport narrowed by the zoom factor plus a matching deviceScaleFactor, the same technique the lab at the end of this skill uses. The script below keeps the window at 1280px and measures this lesson's rule and a vw-heavy rule at five zoom levels. Growth is the size on screen, CSS px × zoom, divided by the size at 100%:
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';
const rules = {
lesson: 'clamp(1.75rem, 1.2rem + 2.2vw, 3rem)',
vwHeavy: 'clamp(1rem, 0.5rem + 5vw, 6rem)',
};
const windowWidth = 1280;
const browser = await chromium.launch();
const base = {};
for (const zoom of [1, 2, 3, 4, 5]) {
// Zoom shrinks the CSS viewport and draws each CSS px with `zoom` device px.
const page = await browser.newPage({
viewport: { width: Math.round(windowWidth / zoom), height: 900 },
deviceScaleFactor: zoom,
});
await page.goto(pathToFileURL('index.html').href);
const parts = [];
for (const [name, rule] of Object.entries(rules)) {
const css = await page.$eval('.fluid', (el, value) => {
el.style.fontSize = value;
return parseFloat(getComputedStyle(el).fontSize);
}, rule);
base[name] ??= css; // the 100% size, measured first
const growth = (css * zoom) / base[name];
parts.push(`${name} ${css.toFixed(2)} CSS px, ${growth.toFixed(2)}x`);
}
const width = await page.evaluate(() => innerWidth);
console.log(`${zoom * 100}% (${width}px wide): ${parts.join(' | ')}`);
await page.close();
}
await browser.close();100% (1280px wide): lesson 47.36 CSS px, 1.00x | vwHeavy 72.00 CSS px, 1.00x
200% (640px wide): lesson 33.28 CSS px, 1.41x | vwHeavy 40.00 CSS px, 1.11x
300% (427px wide): lesson 28.59 CSS px, 1.81x | vwHeavy 29.35 CSS px, 1.22x
400% (320px wide): lesson 28.00 CSS px, 2.36x | vwHeavy 24.00 CSS px, 1.33x
500% (256px wide): lesson 28.00 CSS px, 2.96x | vwHeavy 20.80 CSS px, 1.44xWCAG 2.2 success criterion 1.4.4 Resize Text (level AA) asks that, except for captions and images of text, text can be resized without assistive technology up to 200 percent without loss of content or functionality. Its Understanding document adds two points. One text-scaling mechanism the browser supports, such as zoom, is enough. And text does not have to double at exactly the 200% step or inside the same breakpoint, but it should be possible to reach twice the 100% size in some way, for example at a higher zoom level.
This lesson's heading reaches 2.36x at 400% zoom, where the 1.75rem minimum takes over, so it can reach double size; a reader at 200% still sees it only 1.41 times larger while body text doubles. The vw-heavy heading reaches only 1.44x even at 500%, the highest zoom Chrome offers, so it fails. Three habits help:
- Keep a generous rem term in the middle value. Rem is the part zoom enlarges. Rem is about 40% of this lesson's heading at 1280px, against 11% of the vw-heavy one, and that is why one grows 1.41x at 200% and the other 1.11x.
- Keep the maximum no more than about 2.5 times the minimum. At high zoom the narrow viewport pushes the heading down to its minimum. At 500% zoom that minimum looks 5 × min on screen. Twice the 100% size is at most 2 × max, so the heading can double if 5 × min ≥ 2 × max, that is, if max ≤ 2.5 × min. Here 3rem / 1.75rem is 1.7; 6rem / 1rem is 6.
- Check the computed size at 100% and 200% zoom, and at higher levels if 200% falls short. Multiply the computed size by the zoom factor, which is
devicePixelRatioon a standard display, to get the size on screen, as the script does.
06. Check your understanding
07. Apply it
On the product listing page from this skill's practice task:
- Write the base stylesheet for 320px first, then open the browser and widen until something looks wrong; add a
min-widthem breakpoint there, and repeat once. - Give the page title a
clamp()size with a rem component in the middle, check the computed font size at 320, 768 and 1280px with the script pattern above, then run the zoom script against it and note the growth at 200% and 400%. - Wrap one product card in a
container-type: inline-sizewrapper and let it switch to a horizontal layout when its container reaches 480px; confirm the same card stays stacked inside a narrow rail.
Check each feature you used on web.dev/baseline and note its status in your notes.
08. Review prompt
Without looking back: why is mobile-first with min-width queries easier to keep correct than desktop-first with max-width overrides? What do the three arguments of clamp() mean, and why keep a rem term in the middle one? Why does a vw-heavy heading grow less than body text at 200% zoom, and what does WCAG 1.4.4 ask for? What does a media query measure, and what does a container query measure instead? Where does container-type go, and what does a Baseline status tell you before you use a feature?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.