Running Lighthouse in Chrome DevTools it says CLS (Cumulative Layout Shift) needs improvement.
I’m aware of that modern browsers now set the default aspect ratio of images based on an image's width and height attributes. Hence best practice is that width and height attributes should be set to prevent layout shifts.
Despite this I have omitted setting width and height attributes since this is the only way I can get it to work the way I want (please see my code below).
Because I’m having images in WebP format (with png fallbacks) I’m forced to use the <picture> element (so that the browsers not supporting WebP get the png version of the image). Please note I’m using differently-sized versions of the same image.
Hence if I didn't have used WebP format I would go along with <img> solely and not <picture>. Problem would then have been solved thanks to the aspect-ratio.
As you can see in the code snippet below there are two versions of the same image in this particular example. Setting width="245" and height="600" in <img> result in that both my two differently-sized versions of the same image get the maximum size of 245 x 600px (it will of course scale down in accordance with smaller viewports). For wider viewports (min-width: 813px) according to my media query I'm serving the larger version of the same image but setting width and height in <img> the image scales down to 245 x 600px.
Now to my question/s; If possible, what can I do to be able to set the width and height attributes for my <img> element within my <picture> element to prevent layout shifts (and also get other benefits for doing so such as faster load times)? Hence, how do I get the browsers to make use of the aspect ratio to show my images the correct way?
I would really appreciate someone’s guidance with this.
Thanks / Carl
<picture>
<source
media="(max-width: 812px)"
srcset="image-245w.webp"
type="image/webp"
>
<source
media="(min-width: 813px)"
srcset="image-332w.webp"
type="image/webp"
>
<source
media="(max-width: 812px)"
srcset="image-245w.png"
type="image/png"
>
<source
media="(min-width: 813px)"
srcset="image-332w.png"
type="image/png"
>
<img class="img-fluid" src="image-245w.png" alt="image">
</picture>