Sub topic 11
Putting picture, srcset, and sizes together
This chapter assumes you know srcset with w descriptors, the sizes attribute, and the basic picture element with media and type. You should also be comfortable with CSS media queries and viewport units. Here you combine the three techniques in one element, and you will see where the combination breaks.
Two decisions, made in order
Each technique answers a different question.
picturewithsourceanswers: which kind of image should be used? The choice can depend on the format the browser supports (type) or on the layout (media).srcsetwithsizesanswers: which size of that image should be downloaded?
When you combine them, the browser makes the decisions in sequence. It first walks the source elements from top to bottom and stops at the first one that matches. Then it applies the normal srcset and sizes selection inside that source. If no source matches, it uses the img element's own srcset and sizes.
A source with no media always matches on that test. A source with no type always matches on that test. A source with neither matches every time, so any source after it is never used.
A first combined example
This example uses one landscape crop for wide viewports and one square crop for narrow ones. Both crops are in WebP, and each has two widths.
<picture>
<source
media="(min-width: 50em)"
type="image/webp"
srcset="hero-wide-800.webp 800w, hero-wide-1600.webp 1600w"
sizes="100vw">
<source
type="image/webp"
srcset="hero-narrow-400.webp 400w, hero-narrow-800.webp 800w"
sizes="100vw">
<img
src="hero-narrow-800.jpg"
srcset="hero-narrow-400.jpg 400w, hero-narrow-800.jpg 800w"
sizes="100vw"
width="800"
height="800"
alt="A sailor looking out to sea">
</picture>Consider a 1280 px wide viewport at a device pixel ratio of 2. The first source matches both media and type. With sizes="100vw" the slot is 1280 CSS pixels, so the browser needs about 2560 device pixels. It picks hero-wide-1600.webp, the largest candidate. On a 390 px wide phone at a ratio of 3, the first source fails its media test. The second matches, and the slot of 390 CSS pixels needs about 1170 device pixels. It picks hero-narrow-800.webp.
Where each attribute goes
The img element is the one that renders. The source elements only supply candidates. This affects where you put each attribute.
| Attribute | Goes on | Notes |
|---|---|---|
| `src` | `img` | Required. Fallback when nothing else is chosen. |
| `alt` | `img` | Only the `img` is exposed to assistive technology. |
| `srcset`, `sizes` | `source` and `img` | Each `source` has its own set. The `img` set is used only when no `source` wins. |
| `media`, `type` | `source` | Not valid on `img`. |
| `loading`, `class`, `id` | `img` | CSS and loading hints apply to the `img`, not to `source`. |
| `width`, `height` | `img` | Reserve layout space. See the aspect ratio gotcha below. |
If you style the image, target the img (for example picture img). The picture element itself is not what displays the pixels.
Gotcha: the fallback loses the art direction
The earlier example has a subtle problem. Suppose a desktop browser does not support WebP. It skips the first source because of type, and it skips the second one too. It then uses the img, which holds the narrow square crop. That user gets the wrong crop on a wide screen.
The cause is that the type test and the media test are both applied to each source. A source that fails on type cannot be rescued by a later source. To fix it, add a JPEG source for each crop. The JPEG source needs no type, because JPEG is the baseline.
<picture>
<source
media="(min-width: 50em)"
type="image/webp"
srcset="hero-wide-800.webp 800w, hero-wide-1600.webp 1600w"
sizes="100vw">
<source
media="(min-width: 50em)"
srcset="hero-wide-800.jpg 800w, hero-wide-1600.jpg 1600w"
sizes="100vw">
<source
type="image/webp"
srcset="hero-narrow-400.webp 400w, hero-narrow-800.webp 800w"
sizes="100vw">
<img
src="hero-narrow-800.jpg"
srcset="hero-narrow-400.jpg 400w, hero-narrow-800.jpg 800w"
sizes="100vw"
width="800"
height="800"
alt="A sailor looking out to sea">
</picture>The order is now: wide WebP, wide JPEG, narrow WebP, narrow JPEG (the img). The pattern is that you list every crop-and-format pair, from most specific to least specific. The number of files grows as crops × formats × widths, so keep each list short.
Gotcha: `media` on source is not `media` in sizes
Both features use media conditions, and people often confuse them.
- The
mediaattribute onsourcechooses whichsourceis used. It selects between different images, such as crops. - The conditions inside
sizesdescribe the layout width of the slot for the chosen image. They do not choose between images.
Use media when the content of the image should change. Use sizes when the same image is displayed at different layout widths. A page can have both. A wide crop can fill 100vw, while the narrow crop is shown at 100vw on phones, and a three-column layout can later put a different width in the sizes list of the img.
Keep sizes truthful. If the CSS makes the image 50% of the viewport and sizes says 100vw, the browser downloads a file twice as large as needed. Your CSS and your sizes value must be kept in step by hand.
Gotcha: different crops, different aspect ratios
The width and height attributes on the img set an aspect ratio that reserves space before the file loads. In the example the img is 800 by 800, which matches the square crop. The wide crop has a different ratio, perhaps 2:1. If the page reserves a square and then shows a 2:1 image, the content below jumps, which is the layout shift you wanted to avoid.
You have two options:
- Put
widthandheighton eachsourceas well. The HTML specification allows these attributes onsourceinsidepicture, and current browsers use them to compute the ratio for the selected source. Check support in the browsers you target. - Set the ratio in CSS with a media query that mirrors the
mediacondition of thesource.
picture img {
display: block;
width: 100%;
height: auto;
aspect-ratio: 1 / 1;
}
@media (min-width: 50em) {
picture img {
aspect-ratio: 2 / 1;
}
}The CSS breakpoint must equal the media value on the source (50em here). If they differ, there will be a range of viewport widths where the wrong ratio is reserved.
Combining with lazy loading
The loading attribute goes on the img, and it applies to whichever source is chosen. For a hero image that is visible on first load, do not use loading="lazy". For images below the fold, add it:
<picture>
<source
type="image/avif"
srcset="gallery-400.avif 400w, gallery-800.avif 800w, gallery-1600.avif 1600w"
sizes="(min-width: 40em) 50vw, 100vw">
<source
type="image/webp"
srcset="gallery-400.webp 400w, gallery-800.webp 800w, gallery-1600.webp 1600w"
sizes="(min-width: 40em) 50vw, 100vw">
<img
src="gallery-800.jpg"
srcset="gallery-400.jpg 400w, gallery-800.jpg 800w, gallery-1600.jpg 1600w"
sizes="(min-width: 40em) 50vw, 100vw"
width="1600"
height="1067"
loading="lazy"
alt="Boats moored in a harbor">
</picture>This one has no art direction, so there is no media on any source. It is the format-switching case, and the three sizes values are identical. Duplicating sizes is the cost of the markup. If you generate your HTML from a template or a build step, define the string once.
Checking the result
Because there are several layers, check which file the browser actually picked. In the browser console, currentSrc gives the URL of the chosen file for any img, including one inside picture.
const img = document.querySelector('picture img');
console.log(img.currentSrc);
console.log(window.devicePixelRatio);Run this at several viewport widths and ratios. The developer tools network panel shows the same information as the request list. A browser may keep a larger file it has already loaded when you shrink the window, so reload the page to test a smaller slot.
If the wrong crop appears, check source order and the media values first. If the right crop is too large or too small, check sizes against the CSS. If a format is missing, check the type string and that the server returns the matching Content-Type.
Common errors
- Placing a
type-onlysourcebefore amediasource, which hides the art-directed crop. - Omitting the JPEG
sourcefor the wide crop, so non-WebP browsers get the narrow crop on large screens. - Putting
alt,loading, orclassonsourceinstead ofimg. - Writing
sizesthat disagrees with the CSS width. - Reserving one aspect ratio when crops have different ratios.
- Using
loading="lazy"on the main image that is visible when the page opens.
Exercise
A page uses <picture> with a first <source type="image/avif" srcset="a-wide.avif"> and a second <source media="(min-width: 50em)" srcset="a-wide.jpg">, followed by an img with a square JPEG. A desktop browser supports AVIF. Which file does it load at a 1200 px wide viewport, and what is the problem with the order if the AVIF file is a square crop and the JPEG is a wide crop?
Show answer
It loads a-wide.avif, because the first source matches (it has no media condition and the browser supports AVIF). The second source is never reached. If the AVIF is a square crop and the JPEG is the wide crop, desktop users see the square crop. The fix is to put the media source first, with its own type-specific AVIF version of the wide crop before the wide JPEG, and to list the square AVIF after them.
Exercise
You add a wide 2:1 crop for viewports of 50em and up, but your img has width="800" and height="800". What layout problem can occur on wide screens, and name two ways to fix it?
Show answer
The page reserves a square space, but the 2:1 image fills a shorter box once it loads, so content below shifts. Fix it by adding width and height attributes to the wide source (where browsers support that), or by setting aspect-ratio in CSS with a media query that uses the same 50em breakpoint as the source's media attribute.