by
clemens
(19.11.2021)
Using <Source> and 'srcset' to force browser to choose correct image on mobile
tl;dr
When using responsive images using <picture>
and the sizes
attribute is not enough to force the browser to use a small
image on mobile. Instead you need to provide multiple <source>
tags with the media="(max-width: 200px)"
attribute set.
Instead of providing a couple of images in a single <source>
tag with the sizes
attribute, like so:
<picture>
<source srcset="tiny.avif 250w, small.avif 500w, large.avif 1000w"
type="image/avif"
sizes="(max-width: 250px) 100vw,
(max-width: 500px) 100vw
(max-width: 1000px) 100vw">
<!-- set the fallback image as src that should work on all screen sizes -->
<img src="small.avif">
</picture>
you should instead provide a <source>
tag for each screen cutoff point:
<picture>
<source srcset="tiny.avif 250w"
type="image/avif"
media="(max-width: 250px)"
sizes="100vw">
<source srcset="small.avif 500w"
type="image/avif"
media="(max-width: 500px)"
sizes="100vw">
<source srcset="large.avif 1000w"
type="image/avif"
media="(max-width: 1000px)"
sizes="100vw">
<!-- set the fallback image as src that should work on all screen sizes -->
<img src="small.avif">
</picture>