Sub topic 8
The picture element and source selection order
This chapter covers how picture and its source children work, and in what order the browser evaluates them. It assumes you know the img element with src and alt, basic CSS media queries, and how srcset with w descriptors and sizes work. Later chapters build on this one to cover format switching, art direction, and combining all the techniques.
What picture is for
The img element with srcset and sizes lets the browser choose between files that show the same image at different resolutions. The browser makes that choice, and you only give hints. The picture element solves two problems that srcset cannot:
- Art direction: you want a different crop or composition at different viewport widths. For example, you may want a wide landscape crop on desktop and a tight square crop on a phone.
- Format switching: you want to offer a modern format such as AVIF or WebP while keeping a JPEG for browsers that cannot decode the newer formats.
With picture, you give the browser a list of conditions. The browser follows them instead of choosing freely.
The structure of a picture element
A picture element contains zero or more source elements, followed by exactly one img element. The img is required. It does the actual rendering, and it is the fallback.
<picture>
<source media="(min-width: 50em)" srcset="hero-wide.jpg">
<img src="hero-narrow.jpg" width="800" height="800" alt="A sailor looking out to sea">
</picture>Three points about this structure matter:
- The
pictureandsourceelements are not rendered themselves. They are wrappers that influence which URL theimgdisplays. - The
imgis always the element that appears on the page. Itsalt,width,height,loading, andclassattributes apply to the displayed image. Puttingalton asourcehas no effect. - If the
imgis missing, or asourcecomes after it, thesourceis ignored and nothing is displayed.
Because the img does the rendering, CSS selectors and styles target the img. A rule such as picture { width: 100%; } styles the wrapper, not the image. Write picture img { width: 100%; height: auto; } instead.
The source selection order
The browser reads the source elements from top to bottom. For each one, it asks whether the source is eligible. The first eligible source is used, and the browser stops looking. If no source is eligible, it uses the img element's own src and srcset.
A source is skipped when any of these is true:
- It has a
mediaattribute and the media condition does not match the current viewport. - It has a
typeattribute and the browser does not support that MIME type. - It has no usable
srcset.
If a source has neither media nor type, it always matches. Any sources after it are then unreachable.
Note that the first match wins. The browser does not look for the best match. It also does not compare the sources against each other. This is why order is the central rule of picture.
A worked example of ordering
Consider this markup:
<picture>
<source media="(min-width: 30em)" srcset="medium.jpg">
<source media="(min-width: 60em)" srcset="large.jpg">
<img src="small.jpg" width="600" height="400" alt="A harbor at dawn">
</picture>You may expect a 70em-wide viewport to get large.jpg. It does not. The first source matches at 30em and wider, so every viewport of 30em or more picks medium.jpg. The second source never runs.
There are two ways to fix this. The first is to order the sources from the most specific condition to the least specific:
<picture>
<source media="(min-width: 60em)" srcset="large.jpg">
<source media="(min-width: 30em)" srcset="medium.jpg">
<img src="small.jpg" width="600" height="400" alt="A harbor at dawn">
</picture>The second is to use non-overlapping ranges, so the order no longer matters:
<picture>
<source media="(min-width: 60em)" srcset="large.jpg">
<source media="(min-width: 30em) and (max-width: 59.999em)" srcset="medium.jpg">
<img src="small.jpg" width="600" height="400" alt="A harbor at dawn">
</picture>When you use min-width conditions, put the largest first. When you use max-width, put the smallest first. Mixing the two in one list is where most ordering bugs begin.
What each source can carry
A source inside picture accepts these attributes:
| Attribute | Purpose |
|---|---|
| `srcset` | Required. One or more candidate URLs, with `x` or `w` descriptors, or a single bare URL. |
| `sizes` | Display width hint. Used only when `srcset` uses `w` descriptors. |
| `media` | A media condition. The source is skipped if it does not match. |
| `type` | A MIME type. The source is skipped if the browser does not support it. |
| `width`, `height` | Intrinsic dimensions of the source's images. Supported in current browsers, and useful for aspect ratio. |
A source has no src attribute. A bare URL goes in srcset. A source inside picture also has no alt.
Selection happens in two steps
Once a source is chosen, the normal srcset and sizes logic runs inside that source only. The chosen source supplies its own srcset and sizes. The img element's srcset and sizes are not mixed in.
This gives two separate decisions:
- Which source? This is decided by order,
media, andtype. The result is deterministic. Developers control it. - Which candidate in that source? This is decided by the browser, using
worxdescriptors,sizes, the viewport width, and the device pixel ratio. The browser has freedom here and may take into account network conditions or cached files.
A common mistake is to expect media to select among the candidates of a single srcset. It does not. The media attribute answers only whether the source is used at all.
The img element's role
The img element has three jobs inside picture:
- It is the fallback when no source matches. This includes old browsers that do not know
picture. Such browsers ignore the unknown elements and render theimg. - It is the renderer. Whichever URL is chosen, the
imgshows it. - It is the carrier of attributes such as
alt,width,height,loading,decoding, andclass.
This has a practical consequence. Always make the img fallback a file that every browser can display, usually a JPEG or PNG. A fallback in AVIF would leave some users with a broken image.
The img can also have its own srcset and sizes, which apply when the fallback is used. In the next chapters you will see why a complete fallback should have these too.
Dimensions belong on the img
Set width and height on the img so the browser can reserve space before the file arrives. Browsers use these attributes to compute an aspect ratio. In art direction, the crops often have different aspect ratios, so one pair of values cannot describe them all. You can set the width and height attributes on each source as well, and current browsers use the values from the selected source to compute the aspect ratio. Chapter on dimensions covers this in detail.
Common errors
- Source after img. Sources must come before the
img. Later sources are ignored. - Wrong order of media conditions. As shown above, a broad
min-widthplaced first hides narrower, more specific rules. - Missing img. Without it, nothing renders.
- Unsupported type in the fallback. The
imgshould use a format every browser can show. sizeswithxdescriptors. Thesizesattribute is meaningful only withwdescriptors, so it does nothing here.- Styling the picture element. Visual styles belong on the
img. - Wrong or misspelled MIME type. A source with
type="image/jpg"is not valid. The correct value isimage/jpeg. A browser that does not recognize the type skips the source.
Verifying the choice
You can check which file the browser selected through the currentSrc property of the img, not of the picture:
const img = document.querySelector('picture img');
console.log(img.currentSrc);Resize the window and reload to see how the result changes. In some browsers, currentSrc updates on resize without a reload, but this is not guaranteed, so reload when you test. Developer tools show the same information in the Network panel and in the element inspector.
Summary of the rules
- A
pictureholds any number ofsourceelements followed by oneimg. - The browser checks sources in order and uses the first whose
mediaandtypepass. - Inside the chosen source,
srcsetandsizeswork as they do on a plainimg. - If no source passes, the
imgis used. - The
imgrenders the image and carriesaltand the other attributes.
Exercise
A page has this markup. At a viewport 1000 CSS pixels wide, which file is used, and why? What single change makes the 1000-pixel viewport get wide.jpg while the 500-pixel viewport still gets mid.jpg?
<picture>
<source media="(min-width: 30em)" srcset="mid.jpg">
<source media="(min-width: 60em)" srcset="wide.jpg">
<img src="small.jpg" width="600" height="400" alt="A harbor">
</picture>
Show answer
At 1000 CSS pixels, with a 16px base font size, the viewport is 62.5em wide. The first source, with min-width 30em, matches, and the browser stops there, so it uses mid.jpg. The wide.jpg source is never evaluated. Swap the two source elements so the min-width 60em source comes first. Then a 62.5em viewport matches it and gets wide.jpg, while a 500px viewport (31.25em) fails the 60em condition and matches the 30em one, getting mid.jpg.
Exercise
You write a source element with srcset="photo.avif" and type="image/avif", then an img whose src is photo.avif. A user's browser cannot decode AVIF. What do they see, and how do you fix the markup?
Show answer
The browser skips the source because it does not support the type, then falls back to the img, whose src is also AVIF. The user sees a broken image. Change the img src to a widely supported format such as photo.jpg, and keep the AVIF in the source.