Sub topic 13
Responsive images: srcset, sizes, and picture
This chapter assumes you can write an img element with src, alt, width, and height, and that you understand relative and absolute URLs. If any of that is shaky, review the earlier chapters on img basics and image sizing first.
The problem responsive images solve
A single image file is a poor fit for every visitor. A 1600-pixel-wide photo looks sharp on a large, high-density screen. On a small phone it wastes bandwidth, because the phone can never show that many pixels. A 400-pixel file loads fast on the phone but looks blurry on a large display.
HTML solves this by letting you offer several files and describe them. The browser then picks one. There are two separate problems, and each has its own tool:
- Resolution switching. The same picture at different file sizes. You use
srcsetandsizeson animg. - Art direction and format switching. Different crops or different file formats. You use the
pictureelement.
Keeping these two apart is the main idea in this chapter.
Resolution switching with srcset and sizes
Here is the example from the plan.
<img
src="images/hero-800.jpg"
srcset="images/hero-400.jpg 400w, images/hero-800.jpg 800w, images/hero-1600.jpg 1600w"
sizes="(min-width: 900px) 800px, 100vw"
alt="Mountain lake at sunrise"
width="800"
height="450">Each attribute has a job.
srcis the fallback. Browsers that do not understandsrcsetuse it.srcsetis a comma-separated list of candidates. Each candidate is a URL followed by a width descriptor such as800w. Thewmeans "this file is 800 pixels wide". It describes the file, not the screen.sizestells the browser how wide the image will be displayed in the layout. It is a list of media conditions with lengths, and the last entry is the default.alt,width, andheightwork as usual. Setwidthandheightto the intrinsic size of the fallback file, so the browser can reserve space and avoid layout shift.
How the browser chooses
The browser reads the HTML before it has loaded the CSS, so it cannot know the final layout. sizes is how you tell it. The process is:
- The browser evaluates
sizesfrom left to right and takes the first condition that is true. - It gets a display width in CSS pixels. In the example, that is
800pxon viewports at least 900 pixels wide, otherwise100vw(the full viewport width). - It multiplies that width by the device pixel ratio. A 2x screen showing an 800px slot needs 1600 pixels.
- It picks the smallest candidate in
srcsetthat is at least that wide.
For a phone with a 400px-wide viewport and a 2x screen, sizes gives 100vw, which is 400 CSS pixels. The needed width is 800 pixels, so the browser picks hero-800.jpg. For a desktop with a 1200px viewport and a 1x screen, sizes gives 800px, and the browser picks hero-800.jpg as well.
The choice is a hint, not a command. Browsers may pick a larger file on a fast connection, or reuse a file already in the cache. Do not rely on a particular file being chosen.
Common errors with sizes
- Omitting
sizeswhen usingwdescriptors. The browser then assumes the image is100vwwide. If your image is actually small, it downloads a file that is too large. - Using
wdescriptors withoutsizesthat match the real layout. Ifsizessays100vwbut CSS makes the image 300px wide, the browser over-fetches. - Putting a percentage in
sizes. Percentages are not valid there. Usevwor fixed lengths such aspxorem. - Forgetting the default. The last entry has no condition. Without it the value is invalid.
Density descriptors: a simpler case
When the image always displays at the same CSS size, such as a logo, you can use density descriptors instead of widths and skip sizes.
<img
src="images/logo-120.png"
srcset="images/logo-120.png 1x, images/logo-240.png 2x, images/logo-360.png 3x"
alt="Example Co. home"
width="120"
height="40">Here 2x means "use this file on screens with a device pixel ratio of 2". Do not mix w and x descriptors in the same srcset. That makes the attribute invalid.
| Descriptor | Use when | Needs `sizes` |
|---|---|---|
| `w` (width) | The image changes size with the layout | Yes |
| `x` (density) | The image has a fixed CSS size | No |
Art direction and formats with picture
The picture element wraps several source elements and one final img. The browser checks the source elements in order and uses the first one that matches. If none match, it uses the img.
Format switching
Newer formats such as AVIF and WebP are usually smaller than JPEG at similar quality. Not every browser supports every format, so you offer them in order of preference.
<picture>
<source srcset="images/photo.avif" type="image/avif">
<source srcset="images/photo.webp" type="image/webp">
<img src="images/photo.jpg" alt="Street market at dusk" width="800" height="533">
</picture>The type attribute holds a MIME type. A browser that cannot decode that type skips the source without downloading the file. The img is required. It supplies the alt text, the dimensions, and the fallback, and all img attributes such as loading go on it, not on picture.
Art direction
Sometimes a smaller screen needs a different crop, not just a smaller file. A wide landscape photo may shrink until the subject is tiny. A media attribute on source lets you swap in a tighter crop.
<picture>
<source media="(max-width: 600px)" srcset="images/lake-portrait.jpg">
<source media="(min-width: 601px)" srcset="images/lake-wide.jpg">
<img src="images/lake-wide.jpg" alt="Mountain lake at sunrise" width="1200" height="600">
</picture>Unlike sizes, a matching media condition is a rule, and the browser follows it.
Combining both
A source can also carry srcset with w descriptors and sizes. That gives you format switching and resolution switching together.
<picture>
<source
type="image/webp"
srcset="images/hero-400.webp 400w, images/hero-800.webp 800w, images/hero-1600.webp 1600w"
sizes="(min-width: 900px) 800px, 100vw">
<img
src="images/hero-800.jpg"
srcset="images/hero-400.jpg 400w, images/hero-800.jpg 800w, images/hero-1600.jpg 1600w"
sizes="(min-width: 900px) 800px, 100vw"
alt="Mountain lake at sunrise"
width="800"
height="450">
</picture>The list of sizes is repeated on the source and the img. That repetition is normal.
Choosing the right tool
| Goal | Use |
|---|---|
| Same image, several file sizes | `img` with `srcset` and `sizes` |
| Fixed-size image on sharper screens | `img` with `srcset` and `x` descriptors |
| Different file formats | `picture` with `type` |
| Different crops at different widths | `picture` with `media` |
Start with the simplest tool that works. Most photos need only srcset and sizes.
Edge cases and gotchas
- Alt text lives on the
img. Apicturewith noimgshows nothing at all, and animgwithoutaltis an accessibility error. Allsourceelements share the onealt. - Aspect ratio. If the crops in an art-directed
picturehave different ratios, the singlewidthandheighton theimgcan cause layout shift. Control the ratio in CSS, or accept a small shift when the crop changes. - Order matters in
picture. The first matchingsourcewins. Put the most specific or most preferred one first. - Lazy loading.
loading="lazy"on theimgworks withsrcsetandpicture. Do not lazy-load the main image at the top of the page, since it delays what the visitor sees first. - Generate files, do not guess. You need to create every size yourself. An image tool or build step can produce them. A
srcsetentry that points to a missing file gives a broken image on the devices that pick it. - Test in developer tools. The
currentSrcproperty of animgin the browser console shows which file was chosen.
Exercise
A page shows an image at 100% of the viewport width on phones and at 600px wide on screens 800px or wider. You have files that are 300, 600, and 1200 pixels wide named card-300.jpg, card-600.jpg, and card-1200.jpg. Write the srcset and sizes attributes. Then say which file a 2x phone with a 375px-wide viewport is likely to choose.
Show answer
srcset="card-300.jpg 300w, card-600.jpg 600w, card-1200.jpg 1200w" and sizes="(min-width: 800px) 600px, 100vw". The phone's slot is 375 CSS pixels, and at 2x it needs 750 pixels. The smallest file at least that wide is card-1200.jpg. It is a hint, so the browser may choose differently.
Exercise
Why is picture with type the right choice for offering AVIF with a JPEG fallback, but srcset alone is not?
Show answer
srcset on an img chooses between files by width or density and assumes the browser can decode all of them. The type attribute on a source lets the browser skip formats it cannot decode, and the nested img provides the JPEG fallback.