Sub topic 6
How the browser picks a file
This chapter assumes you can write an img with src and alt, read a CSS media query, and use viewport units such as vw. It also assumes you know that one CSS pixel can be backed by several device pixels. The chapter explains how the browser turns srcset, sizes, and picture into one downloaded file. Knowing the steps lets you predict the result and fix surprises.
The selection happens in two stages
The browser first decides which element supplies the candidates, then decides which candidate to download.
- Choose the source element. For a
picture, the browser reads eachsourcefrom top to bottom. It takes the first one whosemediacondition matches and whosetypeit supports. If none qualifies, it uses theimg. - Choose the candidate. Inside the chosen element's
srcset, the browser picks one file by comparing each candidate's density with the screen's device pixel ratio.
Stage one: choosing the element
The picture rules are strict about order. The browser stops at the first source that passes, even if a later one would suit the screen better.
- A
sourcewith nomediaattribute always passes the media test. - A
sourcewith notypeattribute always passes the type test. - A
sourcewhosetypethe browser cannot decode is skipped. - The
imgmust be present as the last child. It is the fallback, and it is also the element that is actually rendered. Thesourceelements only supply a URL for it.
Put the most specific source first. A catch-all source placed above a conditional one hides the conditional one forever.
Stage two, density case: x descriptors
With x descriptors the density is written for you. The browser compares each value with the device pixel ratio (DPR), which is the number of device pixels per CSS pixel.
<img
src="photo-400.jpg"
srcset="photo-400.jpg 1x, photo-800.jpg 2x"
width="400"
height="300"
alt="A lighthouse on a rocky coast at sunset">On a DPR 2 screen the browser picks photo-800.jpg. On a DPR 1 screen it picks photo-400.jpg. On a DPR 3 screen no candidate reaches 3, so it takes the largest, photo-800.jpg. A candidate with no descriptor counts as 1x.
Stage two, width case: w descriptors and sizes
A w descriptor states the file's intrinsic width in pixels. It says nothing about how big the image will be on the page. The browser needs that second number, and it must have it before layout, because it chooses the file while it scans the HTML. That is why sizes exists.
The browser works in three steps:
- Read
sizesfrom left to right. Use the length of the first entry whose media condition is true. The last entry has no condition and is the default. Ifsizesis missing, the default is100vw. - Convert that length to CSS pixels. This is the source size.
- For each candidate, compute density as
w / source size. Then pick the smallest candidate whose density is at least the DPR. If none reaches it, pick the largest.
Take this markup:
<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">With a 16px default font size, 60em is 960px and 40em is 640px. The table walks through three devices.
| Viewport width | DPR | Matching sizes entry | Source size | Needed width | Candidate densities (400w, 800w, 1600w) | Chosen file |
|---|---|---|---|---|---|---|
| 1200px | 2 | 33vw | 396px | 792px | 1.01, 2.02, 4.04 | photo-800.jpg |
| 800px | 1 | 50vw | 400px | 400px | 1.00, 2.00, 4.00 | photo-400.jpg |
| 390px | 3 | 100vw (default) | 390px | 1170px | 1.03, 2.05, 4.10 | photo-1600.jpg |
The 390px phone gets the 1600-pixel file, because the 800-pixel file has density 2.05 and the screen needs 3. The 1200px desktop gets the 800-pixel file even though the viewport is wide, because the image only fills a third of it.
The same logic as code
This small Node script reproduces the arithmetic. It is a model of the rule, not the browser's real code.
function pickCandidate(candidates, sourceSize, dpr) {
const sorted = [...candidates].sort((a, b) => a.w - b.w);
const needed = sourceSize * dpr;
const match = sorted.find((c) => c.w >= needed);
return match ?? sorted[sorted.length - 1];
}
const candidates = [
{ url: 'photo-400.jpg', w: 400 },
{ url: 'photo-800.jpg', w: 800 },
{ url: 'photo-1600.jpg', w: 1600 },
];
console.log(pickCandidate(candidates, 396, 2).url); // photo-800.jpg
console.log(pickCandidate(candidates, 400, 1).url); // photo-400.jpg
console.log(pickCandidate(candidates, 390, 3).url); // photo-1600.jpgRules that cause common errors
- Do not mix
xandwin onesrcset. The list becomes invalid and browsers may ignore it. sizesonly works withwdescriptors. Withxdescriptors the browser ignores it.sizesdoes not accept percentages. Usevw,px,em, orcalc(), for examplecalc(100vw - 2rem).- The first true condition wins. Order entries from the widest breakpoint to the narrowest when you use
min-width. Order them from narrowest to widest when you usemax-width. - A missing
sizesmeans100vw. If the image is displayed at 300px but the browser assumes the full viewport, it downloads a file far larger than needed. sizesdoes not resize the image. CSS controls the displayed width.sizesonly describes that width to the browser, so the two must agree.
The browser may choose differently
The specification lets the browser override the arithmetic. You will see these cases in practice:
- Cache reuse. If a larger candidate is already cached, the browser may use it instead of fetching the ideal one.
- Resizing up. When a window grows, browsers fetch a larger file if needed. When it shrinks, they usually keep the file they already have.
- Data saving. Some browsers lower the effective density on slow or metered connections.
- Rounding. The browser may round or adjust density comparisons slightly, so a density of 1.99 might still count.
Observing the result
The currentSrc property reports the URL the browser selected. Read it after the image has loaded, because selection may not be complete when the script first runs.
const img = document.querySelector('img');
function report() {
console.log('Selected:', img.currentSrc);
console.log('Device pixel ratio:', window.devicePixelRatio);
console.log('Displayed width:', img.clientWidth);
console.log('Intrinsic width:', img.naturalWidth);
}
if (img.complete) {
report();
} else {
img.addEventListener('load', report);
}Compare naturalWidth with clientWidth * devicePixelRatio. If the first is far larger, you are sending too many pixels. If it is smaller, the image is being upscaled and will look soft.
Exercise
An image has srcset="a-300.jpg 300w, a-600.jpg 600w, a-1200.jpg 1200w" and sizes="(min-width: 50em) 40vw, 100vw". A phone has a 360px-wide viewport and DPR 2. A laptop has a 1000px-wide viewport and DPR 1. Which file does each device choose, assuming a 16px default font size?
Show answer
The phone does not match 50em (800px), so the source size is 100vw = 360px. It needs 360 × 2 = 720 pixels. The smallest candidate at or above 720 is a-1200.jpg. The laptop matches 50em, so the source size is 40vw = 400px. It needs 400 × 1 = 400 pixels. The smallest candidate at or above 400 is a-600.jpg.
Exercise
A page uses a picture element with a first source of media="(min-width: 30em)" and a second source of media="(min-width: 60em)". On a 1200px-wide viewport, which source is used, and how do you fix the order?
Show answer
The first source is used, because it matches first and the browser stops there. The 60em source can never win. Put the (min-width: 60em) source first, then the (min-width: 30em) source, then the img fallback.