Sub topic 12
Serving the right size with srcset and sizes
This chapter assumes you know the img element, basic CSS widths, and how breakpoints work in a responsive layout. You should also know why an image can look blurry when it is too small. Here you will learn how the browser picks one file from several candidates, and how to write srcset and sizes so it picks well.
The problem: one file cannot fit every screen
A single hero.jpg forces a trade-off. If it is 2400 pixels wide, phones download far more data than they can show. If it is 600 pixels wide, it looks soft on a large or high-density screen.
The fix is to export the same photo at several widths and let the browser choose. The browser knows things you do not know when you write the HTML: the viewport width, the screen's pixel density, and sometimes the network conditions or user data-saver settings.
This chapter is about resolution switching: the same crop at different sizes. Serving a different crop at a breakpoint is art direction, which the picture element handles.
How srcset works
srcset is an attribute on img that lists candidate files. Each candidate has a URL and a descriptor. The most useful descriptor is w, which states the file's intrinsic width in pixels.
<img
src="team-800.jpg"
srcset="team-400.jpg 400w, team-800.jpg 800w, team-1600.jpg 1600w"
sizes="(min-width: 960px) 50vw, 100vw"
width="800" height="600"
alt="Four colleagues around a whiteboard">Three details matter here:
- The
wvalue is the real pixel width of the file, not the width it will display at. A 1600-pixel-wide file is1600w. srcis the fallback. Browsers that do not understandsrcsetuse it, and so do some tools that read onlysrc. Point it at a reasonable middle size.- Without
sizes, the browser assumes the image will be 100vw wide (the full viewport). That is wrong for any image in a column or a grid, so it will often download a file that is too large.
How sizes works
sizes tells the browser how wide the image will be displayed, before the CSS has loaded and before layout runs. The browser needs this information early because it starts downloading images while it is still parsing HTML.
The value is a comma-separated list. Each item except the last is a media condition followed by a width. The browser uses the first condition that matches. The last item is the default with no condition.
sizes="(min-width: 960px) 50vw, 100vw"This reads: at 960px or wider, the image is half the viewport width; otherwise it is the full viewport width.
You can use vw units, pixels, or calc(). If your layout has a fixed maximum width, say so:
sizes="(min-width: 1200px) 600px, (min-width: 700px) 50vw, 100vw"Above 1200px the image stops growing at 600 CSS pixels, so asking for more would waste bytes.
How the browser chooses
The browser does a small calculation:
- It reads
sizesand finds the display width in CSS pixels. - It multiplies that by the device pixel ratio (DPR). A DPR of 2 means two physical pixels per CSS pixel.
- It picks the smallest candidate in
srcsetwhose width is at least that number.
Take a 400 CSS pixel slot on a DPR 2 phone. The target is 800 pixels, so the browser picks team-800.jpg. On a DPR 1 desktop showing a 480px slot, it picks team-800.jpg as well, because 400 is too small. The browser may also choose differently from this calculation. For example, it may reuse a larger file already in the cache, or choose a smaller one when data-saving is on. The spec treats your list as an offer, not a command.
The diagram below follows the same steps.
Choosing which widths to export
Do not export every size. Each extra file costs storage and cache space, and gives little benefit when candidates are close together. A common approach is to space candidates so each is roughly 1.5 to 2 times the previous one, such as 400, 800, 1200, and 1600.
Set the top of the range from your layout, not from the original photo. If the largest slot is 800 CSS pixels wide and you support DPR 2, 1600 pixels is enough. A 4000-pixel export adds weight without visible gain.
Never upscale. If the source photo is only 1200 pixels wide, list at most 1200w. Enlarging it in an editor produces a bigger file with no extra detail. See the earlier chapter on checking quality and resolution.
The x descriptor for fixed-size images
If an image always displays at the same CSS width, such as a 120px avatar, you do not need sizes. Use density descriptors instead:
<img
src="avatar-120.jpg"
srcset="avatar-120.jpg 1x, avatar-240.jpg 2x, avatar-360.jpg 3x"
width="120" height="120"
alt="Portrait of Maria Lopez">You cannot mix w and x descriptors in one srcset. If the image width changes with the layout, use w and sizes.
Combining with CSS cropping
srcset and sizes work with the CSS from the previous chapter. The attributes control which file downloads, and CSS controls how it fills the box.
<div class="hero">
<img
src="hero-1200.jpg"
srcset="hero-600.jpg 600w, hero-1200.jpg 1200w, hero-2400.jpg 2400w"
sizes="100vw"
width="1200" height="675"
alt="A baker lifting a loaf from a stone oven">
</div>.hero img {
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
object-fit: cover;
object-position: 30% 40%;
}Every file in the set must share the same crop and aspect ratio. If hero-600.jpg were cropped differently from hero-2400.jpg, the subject would jump when the browser switched files, for example after a window resize or a move to a second monitor.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Large file on a small phone | `sizes` missing, so the browser assumes 100vw | Add `sizes` that matches the real layout |
| Blurry image on a sharp screen | Largest candidate is too small for DPR 2 | Add a candidate at twice the largest display width |
| Wrong file chosen, according to DevTools | `sizes` does not match the CSS | Update `sizes` whenever the layout changes |
| Subject moves when the window resizes | Candidates have different crops | Export all widths from one cropped master |
| Layout jumps while loading | `width` and `height` are missing | Add both attributes with the file's ratio |
| `srcset` ignored | `w` and `x` descriptors mixed, or a comma missing | Use one descriptor type and check the commas |
Debugging which file loaded
Open the browser's developer tools and use the Network panel, filtered to images. Resize the window, then reload. The cached file can hide changes, so tick "Disable cache" while testing.
You can also read the choice from the page. In the console, document.querySelector("img").currentSrc returns the URL the browser selected. It updates after the choice changes.
const img = document.querySelector(".hero img");
console.log(img.currentSrc, img.naturalWidth, img.clientWidth);Compare naturalWidth (the file's pixel width) with clientWidth (the displayed CSS width). Multiply clientWidth by DPR. If naturalWidth is far above that product, you are sending too many bytes. If it is below, the image is being stretched.
Summary
srcsetwithwdescriptors lists candidate files and their real widths.sizesstates the display width so the browser can choose before layout runs.- The browser multiplies display width by DPR and picks the smallest file that covers it.
- Export from one cropped master, in a range set by your layout and your source resolution.
- Use
xdescriptors only for fixed-size images, and never mix them withw.
Exercise
An image sits in a two-column layout. At 900px viewport width and above, it fills half the viewport, but never more than 450px. Below 900px it fills the full viewport. Write the sizes value. Then say which file from srcset="a-400.jpg 400w, a-800.jpg 800w, a-1200.jpg 1200w" a DPR 2 screen with a 1000px-wide viewport would likely pick.
Show answer
sizes="(min-width: 900px) min(50vw, 450px), 100vw". At 1000px the slot is min(500, 450) = 450 CSS pixels. At DPR 2 the target is 900 physical pixels, so the smallest file at least that wide is a-1200.jpg. (If you write sizes="(min-width: 900px) 450px, 100vw" it works too, because 50vw of 900px is already 450px at the breakpoint and the cap applies from there.)
Exercise
A page has a 300px-wide card image with srcset="card-300.jpg 300w, card-1200.jpg 1200w" and no sizes. The layout is a three-column grid, so the card is about a third of a 1200px viewport. What goes wrong on a DPR 1 laptop, and what is the fix?
Show answer
Without sizes, the browser assumes 100vw, so it computes a 1200px target and downloads card-1200.jpg, even though the card displays at about 400px. The fix is to add a sizes value matching the grid, such as sizes="(min-width: 900px) 33vw, 100vw", and add a mid-range candidate like 600w so the browser has a closer match.