Serving the Right Image with srcset and sizes
Give the browser width descriptors and a slot size so it downloads a sharp image that is no heavier than needed, and switch crops with picture.
Contentsand lesson path
On this page
- Why it matters
- Width descriptors and the slot
- When sizes is missing or wrong
- Density descriptors for fixed-size images
- Art direction with picture
- Measure the results
- 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
Images are usually the heaviest thing on a page, and one file cannot suit every screen. A 1600px-wide photograph is wasted bytes on a 320px phone on a metered connection, while the same 400px file stretched across a large monitor looks soft. Responsive images solve this by offering the browser several files for one image and letting it choose. The choice needs two pieces of information from you: what files exist, and how wide the image will be displayed.
This lesson builds one page with all three mechanisms, width descriptors with sizes, density descriptors, and art direction with picture, then reads the browser's actual choice out of the DOM, so every claim below is a measured download rather than a prediction.
02. Width descriptors and the slot
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive images</title>
<style>
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
padding: 16px;
}
.hero {
display: block;
width: 100%;
height: auto;
}
@media (min-width: 1000px) {
.hero { width: 50%; } /* must match the sizes attribute */
}
.banner {
display: block;
width: 320px;
height: auto;
}
</style>
</head>
<body>
<h1>Choosing an image file</h1>
<img
class="hero"
src="hero-400.png"
srcset="hero-400.png 400w, hero-800.png 800w, hero-1600.png 1600w"
sizes="(min-width: 1000px) 50vw, 100vw"
width="1600"
height="900"
alt="Team at work"
>
<img
class="banner"
src="hero-400.png"
srcset="hero-400.png 400w, hero-800.png 800w, hero-1600.png 1600w"
width="1600"
height="900"
alt="Promotional banner"
>
<img
class="icon"
src="icon-24.png"
srcset="icon-24.png 1x, icon-48.png 2x"
width="24"
height="24"
alt="Basket"
>
<picture class="art">
<source media="(max-width: 599px)" srcset="hero-crop-400.png">
<img
src="hero-800.png"
srcset="hero-400.png 400w, hero-800.png 800w"
sizes="100vw"
alt="Team at work"
>
</picture>
</body>
</html>The hero image lists three files, each with a w descriptor stating its real width in pixels. The sizes attribute tells the browser how wide the image slot will be: from 1000px of viewport upwards the hero fills half the viewport (50vw), otherwise all of it (100vw). That promise matches the stylesheet, which gives the hero width: 100% and switches it to 50% at the same 1000px breakpoint; the two should agree. The browser knows the slot before any stylesheet arrives, which is the whole point: it must pick a file while the page is still loading.
The demo needs no real image files: selection runs on the declared widths, so currentSrc reports the browser's choice even when the files are missing (with one-pixel placeholders in their place the results below are the same). Measured choices for the hero, read back from currentSrc in headless Chromium (via Playwright 1.64.1): at a 1280px viewport on a 1x screen the slot is 640px and the browser picks hero-800.png, the smallest candidate that covers it. At 720px the slot is 720px (the image is actually drawn 688px wide, because the 16px body padding comes off each side; a sizes value slightly larger than the real slot only costs a few extra pixels) and it still picks the 800w file; at 400px the slot is 400px and hero-400.png wins. On a 2x screen at 1280px the slot is still 640px CSS, but the browser doubles it to 1280 device pixels and picks hero-1600.png.
So sizes describes the layout, and the device pixel ratio turns that into a file size. With width descriptors you do not choose the file yourself; you describe the situation and the browser, which knows the network and the screen, decides.
The width="1600" and height="900" attributes on the image do a different job: they give the browser the aspect ratio up front, so it can reserve the right amount of space before any file arrives and the text below does not jump when the image lands. Keep them in step with the natural size of the largest candidate.
03. When sizes is missing or wrong
The banner image has the same srcset as the hero but no sizes attribute, and its CSS displays it at a fixed 320px. Without sizes the browser assumes the default of 100vw. Measured at a 1280px, 1x viewport: the banner downloads hero-1600.png, five times wider than displayed, because the browser believed the slot was the whole viewport.
That is the classic failure mode: sizes that does not match the CSS the reader will actually get. The attribute is a promise about the rendered width; when media queries or component styles change the display size, the promise must change with them. Keep sizes and the layout in step, and re-check both whenever you restyle an image.
The choice is also not frozen forever. When the window is resized after load, the browser re-runs the selection and may fetch a better-fitting file, and the measured currentSrc changes with it. The cache softens the cost of a first choice that later turns out to be small, but the promise in sizes is still what keeps the first download honest.
04. Density descriptors for fixed-size images
The icon in the demo never changes size: it is 24 CSS pixels on every screen. For that case, w descriptors would be clumsy, so srcset also accepts density descriptors: icon-24.png 1x, icon-48.png 2x means "this file suits a 1x screen, that one a 2x screen". Measured, the 1x page picks icon-24.png and the 2x page picks icon-48.png.
Use density descriptors when the display size is fixed and small; use width descriptors with sizes when the image flexes with the layout. Mixing both in one srcset is invalid, so pick per image, not per site.
05. Art direction with picture
Resolution is not the only reason to swap files. On a narrow phone the demo should show a tight crop of the subject; on wider screens the full scene. That is a different image, not a bigger or smaller one, and it is what the picture element is for. A source child carries a media condition and its own srcset; the first matching source wins, and the plain img inside is the fallback that carries the alt text.
Measured: at a 400px viewport the picture shows hero-crop-400.png; from 600px up it falls through to the img and its width descriptors, picking hero-400 or hero-800 as the slot demands. Note the division of labour: picture chooses between different images, srcset and sizes choose between different files of the same image.
06. Measure the results
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';
const browser = await chromium.launch();
const url = pathToFileURL('index.html').href;
const pick = async (scale, width) => {
const page = await browser.newPage({ deviceScaleFactor: scale });
await page.setViewportSize({ width, height: 900 });
await page.goto(url);
const chosen = await page.evaluate(() => {
const selectors = ['.hero', '.banner', '.icon', '.art img'];
return selectors.map((sel) => document.querySelector(sel).currentSrc)
.map((src) => src.split("/").pop());
});
console.log(
`DPR ${scale}, ${width}px viewport: hero ${chosen[0]}, banner ${chosen[1]},`,
);
console.log(` icon ${chosen[2]}, picture ${chosen[3]}`);
await page.close();
};
await pick(1, 1280);
await pick(1, 720);
await pick(1, 400);
await pick(2, 1280);
await pick(2, 400);
await browser.close();DPR 1, 1280px viewport: hero hero-800.png, banner hero-1600.png,
icon icon-24.png, picture hero-800.png
DPR 1, 720px viewport: hero hero-800.png, banner hero-800.png,
icon icon-24.png, picture hero-800.png
DPR 1, 400px viewport: hero hero-400.png, banner hero-400.png,
icon icon-24.png, picture hero-crop-400.png
DPR 2, 1280px viewport: hero hero-1600.png, banner hero-1600.png,
icon icon-48.png, picture hero-800.png
DPR 2, 400px viewport: hero hero-800.png, banner hero-800.png,
icon icon-48.png, picture hero-crop-400.png07. Check your understanding
08. Apply it
Give the product images on your practice listing page real candidates:
- Export one product photo at three widths, say 400, 800 and 1200px, and add them to the card image with
wdescriptors. - Write
sizesthat matches the card's rendered width at each of your breakpoints, then confirm the chosen file at 320, 768 and 1280px with thecurrentSrcscript above. - Find one image on the page that is fixed in size, if only a logo, and give it density descriptors instead.
Record which images changed file at which viewport, so you can spot any sizes promise that no longer matches the CSS.
09. Review prompt
Without looking back: what does a w descriptor state, and what does sizes promise? How does the device pixel ratio change the choice at the same viewport width? What happens when sizes is missing, and what is the default? When are density descriptors the better fit than width descriptors, and which element swaps a different crop rather than a different file size?
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.