When should I set explicit widths/heights for images to increase CLS score?

Always thought it was bad practice, but I'm checking Page Speed Insights and it's telling me to add explicit widths/heights so that it improves my CLS score. I do have a couple images that can be fixed, so I did make them fixed with explicit width and height and that was enough to bump my page to 100 performance. Curious about the nuances though.
9 Replies
ErickO
ErickO•14mo ago
There's 2 reasons to set explicit heigh/width to images actually 1) layout shift: when your images takes longer to load than the html the initial render does not account for height, once your image loads and the size can be calculated it'll re-render the layout and shift it to fit the image, layout shift suckss so you should avoid it 2) performance: if you have many images (or elements in general) that are re-sized after an initial render you are causing something that is called "Browser reflow" which affects performance the more elements you have because the browser has to calculate sizes and layout over and over as the images load (this is why when adding a bunch of elements to the page you want to use a fragment instead of, for example, a loop that adds each element one by one)
vince
vince•14mo ago
ohhh I've experienced all of this firsthand, it's nice to know why the browser behaves like that. makes a ton of sense, thank you Erick! 🙂 So do you think it's worth trying to set explicit widths/heights for images in media queries for common devices as a common rule of thumb, or is it more of a case-by-case basis and how much time I want to put in to optimize loading times for the page?
ErickO
ErickO•14mo ago
eh it depends for the most part you can just set the image's native size on the tag <img src="https://placehold.co/600x400" alt="some image" width="600" height="400"> and in your css make it responsive
img {
width: 100%;
height: auto;
}
img {
width: 100%;
height: auto;
}
ErickO
ErickO•14mo ago
here's some info on it bit of a...science
vince
vince•14mo ago
Ah okay, got it. So basically the browser initializes it to 600x400, and if it needs to still fill in the container, it will, and it mitigates layout shift?
ErickO
ErickO•14mo ago
yeah oh in that article is not mentioned but we now have a property aspect-ratio
vince
vince•14mo ago
I've been trying to set aspect-ratio, doesn't always work... I'll have to look more into it. I feel like this would be a perfect use case for srcset but I don't have multiple different versions of each image haha Thank you for the resource! Looks great
ErickO
ErickO•14mo ago
no problem