Sub topic 5
Telling the Browser How Wide the Image Will Be with sizes
This chapter assumes you know the img element, CSS media queries and viewport units (vw), and the difference between CSS pixels and device pixels. It also assumes you have read the chapter on w descriptors in srcset.
Why srcset alone is not enough
A srcset with w descriptors tells the browser what files exist and how wide each one is. It does not say how wide the image will appear on the page.
The browser needs that second number to choose well, and it needs it early. Browsers start downloading images before CSS has loaded and before layout has run. At that point the browser cannot measure the rendered image. The sizes attribute fills the gap. It is your prediction of the image's layout width, written in the HTML so the browser can read it immediately.
Without sizes, the browser assumes 100vw, which means the image fills the viewport. For an image that fills only a third of the page, that assumption makes the browser download a file that is too large.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 60em) 33vw, (min-width: 40em) 50vw, 100vw"
width="1600"
height="1200"
alt="A lighthouse on a rocky coast at sunset">Anatomy of a sizes value
A sizes value is a comma-separated list. Each entry except the last has the form (media condition) length. The last entry is only a length, and it is the default.
For the example above, the list reads like this:
| Entry | Meaning |
|---|---|
| `(min-width: 60em) 33vw` | When the viewport is at least 60em wide, the image is one third of the viewport width. |
| `(min-width: 40em) 50vw` | Otherwise, when the viewport is at least 40em wide, the image is half the viewport width. |
| `100vw` | In all other cases, the image fills the viewport. |
The browser reads the entries from left to right and uses the length from the first entry whose condition is true. Because the first match wins, order matters.
Order your entries correctly
With min-width conditions, put the largest breakpoint first. If you reverse the order above, (min-width: 40em) is true for every viewport of 40em or wider. The 60em entry is never reached, and wide screens get the wrong length.
With max-width conditions, do the opposite: put the smallest breakpoint first.
<img
src="card-600.jpg"
srcset="card-300.jpg 300w, card-600.jpg 600w, card-1200.jpg 1200w"
sizes="(max-width: 30em) 100vw, (max-width: 60em) 50vw, 25vw"
width="1200"
height="800"
alt="A product card photo">Which lengths are allowed
The length can use vw, em, rem, px, and other absolute or font-relative units. It can also use calc(), which is useful when the layout has fixed padding or gutters:
sizes="(min-width: 50em) calc(50vw - 2rem), calc(100vw - 2rem)"You cannot use percentages. A percentage depends on a parent element's width, and the browser does not know that yet. Use vw and calc() to express the same thing relative to the viewport.
Matching sizes to your CSS
sizes does not change how the image is displayed. Your CSS does that. If the two disagree, the browser still renders the image according to the CSS, but it may have downloaded a file that is too small (blurry) or too large (wasted bytes).
Suppose a page has a content column that is at most 40em wide and centered, with the image filling the column:
.article img {
display: block;
width: 100%;
max-width: 40em;
height: auto;
}The image width is the viewport width on narrow screens and 40em on wide ones. A matching sizes value:
<img
class="article-img"
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 40em) 40em, 100vw"
width="1600"
height="1200"
alt="A lighthouse on a rocky coast at sunset">When your CSS changes, update sizes too. A stale sizes value is a common source of wrong downloads, and nothing warns you about it.
Estimating the width
You do not need pixel-perfect numbers. The browser only needs a value close enough to land on the right candidate. A practical way to get one:
- Open the page in the browser and resize the window.
- Note the viewport widths where the layout changes, such as where a grid goes from one column to two.
- At each range, measure the rendered image width and express it in
vw, or in a fixed unit if it stops growing. - Write the entries from the widest breakpoint to the narrowest.
What the browser does with the number
The browser multiplies the chosen sizes length by the device pixel ratio (DPR). It then picks a candidate from srcset whose width is at least that product, usually the smallest one that qualifies. The next chapter covers the full selection process, but one worked example shows why sizes matters.
Take a viewport of 1200 CSS pixels at DPR 2, using the first example. At 1200px the viewport is below 60em (960px at the default 16px font size)? No: 60em is 960px, so 1200px matches the first entry and the slot is 33vw.
- Slot width: 33% of 1200 = 396 CSS pixels.
- Needed pixels: 396 × 2 = 792.
- Smallest candidate at least 792 wide:
photo-800.jpg.
Now remove sizes. The browser assumes 100vw: 1200 × 2 = 2400 pixels needed. No candidate is that wide, so it picks the largest, photo-1600.jpg. That file is roughly four times the pixel count of the 800px file, and you paid for those bytes for nothing.
The diagram below shows the flow.
Common errors
- Omitting sizes with w descriptors. The browser assumes
100vw. Images that are not full width download oversized files. - Using sizes with x descriptors.
sizesonly works together withwdescriptors. Withxdescriptors it has no effect. - Wrong order of conditions. The first true entry wins, so list
min-widthentries from largest to smallest. - Percentages in sizes. They are invalid. Use
vworcalc(). - A final entry with a condition. The last entry must be a bare length. If every condition fails and there is no default, the whole value is invalid and the browser falls back to
100vw. - Forgetting that sizes describes layout, not the file. Describing a
wdescriptor insizes(for example800pxbecause the file is 800px wide) is a mistake.sizesdescribes the slot on the page.
Checking your sizes value
You can verify a sizes value in the browser console. currentSrc shows which candidate was chosen, and clientWidth shows the width the layout actually gave the image.
const img = document.querySelector('img');
console.log('chosen:', img.currentSrc);
console.log('rendered width:', img.clientWidth);
console.log('DPR:', window.devicePixelRatio);
console.log('needed pixels:', img.clientWidth * window.devicePixelRatio);If needed pixels is far below the intrinsic width of the chosen file, sizes is too large. If it is above, the image will look soft, and sizes may be too small. Resize the window and run the code again at each breakpoint. Some browsers keep a larger file after the window shrinks, so reload the page between tests.
Summary of rules
- Use
sizesonly withwdescriptors. - Write conditions from the widest breakpoint to the narrowest when using
min-width. - End the list with a plain length as the default.
- Use
vw, absolute units, andcalc(). Do not use percentages. - Keep
sizesin step with your CSS.
Exercise
A page shows an image in a three-column grid on viewports of 60em and wider (each image is one third of the viewport width), in two columns from 40em to 60em (half of the viewport), and in one column below 40em (full width). Write the sizes attribute. Then, for a 1000px-wide viewport at DPR 2, work out the slot width and the pixel width the browser needs. The srcset has files at 400w, 800w, and 1600w. Which file does the browser pick?
Show answer
sizes="(min-width: 60em) 33vw, (min-width: 40em) 50vw, 100vw". At 1000px the viewport is wider than 40em (640px) but narrower than 60em (960px)? No: 60em is 960px, and 1000px is wider than that, so the first entry matches and the slot is 33vw = 330 CSS pixels. At DPR 2 the browser needs 660 pixels. The smallest candidate at least 660 wide is the 800w file.
Exercise
Why does a sizes value of "(min-width: 40em) 50vw, (min-width: 60em) 33vw, 100vw" give the wrong result on a 1400px-wide viewport, and how do you fix it?
Show answer
The browser uses the first entry whose condition is true. At 1400px the (min-width: 40em) condition is true, so it picks 50vw and never reaches the 60em entry. Fix it by putting the largest breakpoint first: "(min-width: 60em) 33vw, (min-width: 40em) 50vw, 100vw".