Sub topic 11
Responsive Images with srcset and sizes
This chapter assumes you know basic HTML and CSS, understand CSS pixels and the viewport meta tag, and have read the chapters on fluid layouts and media queries. You will learn how the browser chooses an image file, how to describe your layout to it with sizes, and where this goes wrong.
Why one image file is not enough
A layout that changes across breakpoints changes how wide each image is displayed. A hero image might fill the whole screen on a phone and sit in a 600px column on a desktop. If you ship one large file to everyone, phone users download pixels they cannot see. If you ship one small file, desktop and high-density screens show a blurry image.
Responsive images solve this. You give the browser several versions of the same image and enough information to pick one. The browser knows things you do not: the real viewport width, the screen's pixel density, and often the network conditions or data-saver settings. So the choice is made by the browser, not by your CSS.
There are two separate problems, and HTML has a separate tool for each:
| Problem | Name | Tool |
|---|---|---|
| Same picture, different file sizes | Resolution switching | `srcset` and `sizes` on `<img>` |
| Different crop or different picture per frame | Art direction | `<picture>` with `<source media>` |
This chapter focuses on resolution switching, then shows when to move to art direction.
Device pixels and the width descriptor
A CSS pixel is not always one screen pixel. A screen with a device pixel ratio (DPR) of 2 uses a 2 by 2 grid of physical pixels for each CSS pixel. An image shown at 400 CSS pixels wide needs 800 image pixels to look sharp on that screen.
This is why you need more than one file per layout width. The same 400px slot needs a 400px file at DPR 1, an 800px file at DPR 2, and a 1200px file at DPR 3.
The srcset attribute with width descriptors
Here is the example from the plan.
<img
src="hero-800.jpg"
srcset="hero-480.jpg 480w, hero-800.jpg 800w, hero-1200.jpg 1200w"
sizes="(min-width: 80em) 1200px, 100vw"
alt="A team reviewing a layout on three screen sizes">Each entry in srcset is a file URL followed by a width descriptor. The w unit means the file's intrinsic width in image pixels. It does not mean CSS pixels. hero-480.jpg 480w says "this file is 480 pixels wide."
The src attribute stays as the fallback. Browsers that do not understand srcset use it, and so do some tools and crawlers. Pick a middle size for it.
The alt attribute is required and is the same for every candidate, because they are all the same picture.
The sizes attribute
The browser needs to know how wide the image will be displayed, so it can compare that with the file widths. But the browser reads the HTML and starts downloading images before it has loaded the CSS and computed the layout. So it cannot measure the image slot. sizes is your promise about the slot width, written in the HTML.
sizes is a comma-separated list. Each item except the last is a media condition followed by a length. The browser uses the first condition that matches. The last item is the default and has no condition.
In the example:
(min-width: 80em) 1200pxmeans that when the viewport is at least 80em wide, the image displays at 1200px.100vwis the default: otherwise the image fills the viewport width.
A vw unit is one percent of the viewport width. You can also use calc(), for example calc(100vw - 2rem) for an image inside a page with 1rem of padding on each side.
How the browser picks a file
- It walks through
sizesand takes the first matching length. Call this the slot width. - It multiplies the slot width by the device pixel ratio. This is the target width in image pixels.
- It picks the smallest
srcsetcandidate whose width is at least the target. If none is large enough, it takes the largest. - It may choose differently, for example reusing a file already in the cache or picking a smaller one on a slow connection.
The diagram shows the same logic as a flow.
A worked example
Take a phone with a 390px wide viewport and DPR 3.
- No condition matches
(min-width: 80em), so the slot width is100vw, which is 390px. - The target is 390 × 3 = 1170 pixels.
- The smallest file at least 1170 wide is
hero-1200.jpg.
The browser downloads the 1200px file on the phone, even though the screen is small. That is correct: the phone has many physical pixels. Now take a laptop with a 1440px viewport and DPR 1.
(min-width: 80em)matches. 80em is 1280px at the default 16px font size, and 1440 is larger, so the slot width is 1200px.- The target is 1200 × 1 = 1200 pixels.
- The browser picks
hero-1200.jpg.
And a tablet with a 768px viewport and DPR 1: the slot is 768px, the target is 768, and the smallest file at least that wide is hero-800.jpg.
Matching sizes to the layout
sizes must describe your CSS. When the layout changes at a breakpoint, sizes needs a matching condition. Consider a card grid that has one column on mobile, two columns from 48em, and three columns from 80em, with 1rem gaps and 1rem page padding.
<img
src="card-600.jpg"
srcset="card-320.jpg 320w, card-600.jpg 600w, card-900.jpg 900w"
sizes="(min-width: 80em) calc((80rem - 4rem) / 3),
(min-width: 48em) calc((100vw - 3rem) / 2),
calc(100vw - 2rem)"
alt="Product photo of a blue ceramic mug">Each line mirrors one layout state. List the conditions from widest to narrowest, because the first match wins. Line breaks inside sizes are allowed.
The calculations are approximate on purpose. The browser needs a reasonable estimate, not a pixel-perfect one. An estimate that is off by 10 percent rarely changes which file is picked. An estimate that is off by 2x does.
Keep the breakpoints in sync
sizes repeats your media query breakpoints in a second place. If you change a breakpoint in CSS from 48em to 52em and forget sizes, the browser will choose files for the wrong layout. Options to reduce this risk:
- Keep image sizes next to the breakpoint tokens in your documentation, and review them together.
- Generate the
sizesstring from the same breakpoint list in your build or template code. - Use fewer image layouts. If an image is 100vw at every width,
sizes="100vw"never needs to change.
Choosing the candidate widths
Pick candidate widths that cover the range of target widths you expect. A practical approach:
- Find the smallest and largest slot widths from your layout.
- Multiply by DPR 1 and DPR 2 (DPR 3 only for hero images where detail matters).
- Add candidates so that no two neighbors are more than about 1.5 times apart. Larger gaps waste bytes, because the browser has to round up.
Do not generate a file larger than the original source. Upscaling adds bytes without detail.
Compress each size separately. Modern formats such as WebP and AVIF are smaller than JPEG at the same quality, and you can offer them with <picture>, shown next.
Art direction with the picture element
srcset and sizes assume every file is the same picture at different resolutions. Sometimes the picture itself should change. A wide photo of a team in a meeting room works on desktop, but on a phone the faces become tiny. A tighter crop works better there.
For this, use <picture>. Here, unlike sizes, the browser must obey the media condition.
<picture>
<source
media="(min-width: 48em)"
srcset="team-wide-800.jpg 800w, team-wide-1600.jpg 1600w"
sizes="(min-width: 80em) 1200px, 100vw">
<img
src="team-tall-480.jpg"
srcset="team-tall-480.jpg 480w, team-tall-960.jpg 960w"
sizes="100vw"
alt="Four teammates around a table, reviewing a layout">
</picture>The browser takes the first <source> whose media matches. Inside that source it still does resolution switching with srcset and sizes. If no source matches, it uses the <img>. The <img> element is required, and it carries the alt text.
You can also select by file type with the type attribute, so browsers that support AVIF get it and others fall back.
<picture>
<source type="image/avif" srcset="hero-800.avif 800w, hero-1200.avif 1200w" sizes="100vw">
<source type="image/webp" srcset="hero-800.webp 800w, hero-1200.webp 1200w" sizes="100vw">
<img
src="hero-800.jpg"
srcset="hero-800.jpg 800w, hero-1200.jpg 1200w"
sizes="100vw"
alt="Sunrise over a city skyline">
</picture>Use art direction only when the crop must change. If you only want smaller files, srcset and sizes are simpler and let the browser decide.
Density descriptors: the other srcset syntax
For images with a fixed CSS size, such as a 64px logo or avatar, you can describe files by pixel density instead of width.
<img
src="logo-64.png"
srcset="logo-64.png 1x, logo-128.png 2x, logo-192.png 3x"
width="64"
height="64"
alt="Acme logo">You cannot mix w and x descriptors in one srcset, and x descriptors do not use sizes. Use x when the displayed size never changes, and w plus sizes when it does.
Preventing layout shift
A responsive image still needs to reserve space before it loads. Otherwise the page jumps when the file arrives. Set the width and height attributes to the intrinsic dimensions of the file, and let CSS scale the image.
img {
max-width: 100%;
height: auto;
}Browsers use the width and height attributes to compute an aspect ratio, and height: auto keeps that ratio when max-width shrinks the image. With <picture> and different crops, set the dimensions on the <img> for the crop you expect most often, or set an aspect-ratio in CSS per breakpoint.
For images below the first screen, add loading="lazy". Do not lazy-load the main hero image, because that delays the most important paint. If you can, add fetchpriority="high" to that hero image.
Common errors
- Missing
sizeswithwdescriptors. The browser then assumes the image is 100vw wide. A small thumbnail in a sidebar will download a file sized for the full screen. sizesthat disagrees with the CSS. If CSS shows the image at 50% width andsizessays100vw, the browser downloads files that are too large.- Conditions in the wrong order. The first match wins, so a
(min-width: 48em)condition placed before(min-width: 80em)always matches on large screens and hides the later one. - Using px in
sizeswhereemis used in CSS. Media conditions insizesfollow the same rules as media queries. Keep the units the same as your CSS breakpoints so the two agree when users change their default font size. - Testing with the cache on. Browsers reuse a larger file they already have. Disable the cache in developer tools, and check the Network panel to see which file loaded at each width.
- Expecting a reload to switch files. After you resize the window, a browser may keep the file it already has, since a larger one is fine. Reload to see the choice made fresh at the new width.
- Putting
max-width: 100%on the wrong element. Apply it to the<img>, not to<picture>or<source>.
A short checklist
- Does every
<img>havesrc,alt,width, andheight? - If
srcsetusesw, issizespresent and does it match the CSS at each breakpoint? - Are the candidate widths no more than about 1.5 times apart?
- Is
<picture>used only where the crop or format must change? - Is the hero image eager-loaded and the rest lazy?
Exercise
A product image sits in a layout with 1rem of page padding. It is full width below 48em, and it is half of the content width from 48em up (ignore the gap). The files are p-400.jpg 400w, p-800.jpg 800w, and p-1600.jpg 1600w. Write the sizes attribute. Then say which file a browser picks for a 1000px wide viewport at DPR 2, taking 48em as 768px.
Show answer
sizes="(min-width: 48em) calc((100vw - 2rem) / 2), calc(100vw - 2rem)". At 1000px, 48em matches. The slot is (1000 - 32) / 2 = 484px. At DPR 2 the target is 968 pixels. The smallest file at least 968 wide is p-1600.jpg, because p-800.jpg is too small. If your estimate rounds differently the answer stays the same, since 968 is between 800 and 1600.
Exercise
Your CSS changes the layout breakpoint from 48em to 60em, but the sizes attribute still says (min-width: 48em) 50vw, 100vw. What happens to a 700px wide viewport at DPR 1, and how do you prevent this kind of bug?
Show answer
The CSS shows the image full width at 700px, so the slot is 700px. But sizes matches the 48em condition and says 50vw, which is 350px. The browser picks a file at least 350 wide, so a smaller file is stretched to 700px and looks blurry. To prevent it, update sizes whenever you change a breakpoint, generate sizes from the same breakpoint tokens as the CSS, and review images when breakpoints change.
Exercise
When should you use <picture> instead of srcset and sizes alone?
Show answer
Use <picture> when the image itself must change, such as a different crop for mobile and desktop, or when you offer different file formats such as AVIF and WebP with a JPEG fallback. For the same picture at different resolutions, srcset and sizes on <img> are enough.