Having green web vitals is no longer nice to have. Rather, with recent Google's algorithm's changes, it's became a necessity to pay close attention to how our site performs. Unless, of course, you like your anonymity and would rather not deal with those pesky site visitors; which, I suppose, is perfectly fine too. To each his own.
On the off chance, though, that you actually care about your SEO, you might have come upon a pretty peculiar problem, which I've had a run in with recently. After many years, it is now again recommended to use
height attributes on images, to reduce - at least slightly - CLS.
It is fine and perfectly easy thing to do - as long as you are dealing with images that have a fixed dimensions set, and take exactly the same amount of space on each device and responsive view you have. But what if you have to deal with truly responsive images? For example, an image that:
- on mobiles has 100% available width;
- on small tablets has 75% available width;
- on normal tablets has 500px width;
- on small desktops has 720px width;
- and on normal desktops and up, has 800px width.
How would you deal with it? Which values should go into the
The answer is quite surprising – it doesn't matter.
In most all cases it is perfectly OK to use original image dimensions. Because what is really important for browsers is the aspect ratio. So, as long as you keep it true with the original dimensions, it shouldn't cause any issues.
And that's also confirmed by web.dev, where we read:
Modern browsers now set the default aspect ratio of images based on an image's width and height attributes so it's valuable to set them to prevent layout shifts. Thanks to the CSS Working Group, developers just need to set
heightas normal (...) and the UA stylesheets of all browsers add a default aspect ratio based on the element's existing
When working with responsive images,
srcsetdefines the images you allow the browser to select between and what size each image is. To ensure
<img>width and height attributes can be set, each image should use the same aspect ratio.
Oh, and by the way - while a good starting point, in many cases setting
height alone won't be even close to getting rid of CLS caused by images. Some helpful tips and tricks I learned recently just for such cases – coming soon.