Sub topic 2
How the Browser Picks a File
This chapter assumes basic HTML and CSS, including media queries and viewport units. You should also know that CSS pixels and device pixels can differ, and that JPEG, WebP, and AVIF are image formats.
Choosing a candidate
When an img element has several files, the browser estimates the image's display width and considers the device pixel ratio (DPR). DPR is the ratio between physical device pixels and CSS pixels.
With pixel-density descriptors, 1x targets a one-to-one display and 2x targets a screen needing twice the pixel density:
<img
src="photo-400.jpg"
srcset="photo-400.jpg 1x, photo-800.jpg 2x"
width="400"
height="300"
alt="A lighthouse at sunset">For fluid layouts, use width descriptors such as 400w and 800w. The browser compares these widths with the rendered width and DPR. The sizes attribute tells it the rendered width before layout is complete:
<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 at sunset">The browser may select a larger candidate than the CSS width when the display has a high DPR. It also considers cache state, network conditions, and browser heuristics.
Reserving space with width and height
The width and height attributes describe the image's intrinsic ratio. The browser uses them to reserve space before the file arrives. This prevents layout shift, where content jumps because an image suddenly occupies space.
The attributes do not force the final display size. CSS can still scale the image:
img {
max-width: 100%;
height: auto;
}Selecting sources with picture
The picture element lets the browser test source elements in document order. It uses the first source whose conditions match, then uses the nested img as the fallback.
<picture>
<source media="(min-width: 50em)" srcset="hero-wide.jpg">
<img src="hero-square.jpg" width="800" height="800" alt="A sailor at sea">
</picture>Serving modern formats with a fallback
The type attribute lets the browser skip formats it cannot decode:
<picture>
<source type="image/avif" srcset="photo.avif">
<source type="image/webp" srcset="photo.webp">
<img src="photo.jpg" width="800" height="600" alt="A lighthouse at sunset">
</picture>The JPEG is used when AVIF and WebP are unsupported.
Exercise
Why must the img element remain inside picture?
Show answer
It provides the fallback image and the required alt text when no source is usable.