I've read through a fair number of guides on responsive images, but none seem to cover the intersection of serving different resolutions and setting sizes based on those resolutions to avoid layout shifting.
For example, on desktop, I'd like to load a 128x180px image, and set height
and width
to these values, to appease Lighthouse and avoid any layout shifting. But on mobile, I want to load a 50x48px alternative, and use these as the image dimensions. Do I have to create a new <source>
for each alternative, rather than using srcset
to serve many? Especially when serving multiple formats, this seems insane, as you'd be copy/pasting dozens of times.
<picture>
<source
media="(min-width: 60em)"
width="128"
height="180"
srcset="x.webp"
type="image/webp"
/>
<source
width="50"
height="48"
srcset="y.webp"
type="image/webp"
/>
<source
media="(min-width: 60em)"
width="128"
height="180"
srcset="x.png"
type="image/png"
/>
<img
width="50"
height="48"
src="y.png"
type="image/png"
/>
</picture>
This seems to work, but duplicating this on every picture is quite awful, to be honest. I cannot imagine this is actually the correct method. Is there a better way of doing this, or is this actually correct? Perhaps there's another way to avoid any layout shifting/appease tools like Lighthouse?