We briefly discussed using explicit width and height on image elements earlier in this guide when outlined the importance of avoiding large content layout shifts. If you do not have the image width or height set, this can end up causing a bad CLS (Cumulative Layout Score), as well as a frustrating experience for users. Even though CLS is not a major page performance metric, it is a core metric that needs to be reviewed and addressed as a smooth experience is something that all users want when they land on your website pages. If you have ever landed on a page and started clicking or interacting with buttons, etc., and the content moves around, you know how frustrating it can be. And this can be even more pronounced on mobile devices, where space, or the user’s viewport, is more limited compared to a desktop or laptop display.
Setting explicit width and heights can help the browser to reserve the appropriate space, so that your page does not experience bad layout shifts or appear “janky” to users. Additionally, this helps reduce the main thread work the browser must process and helps with a smoother overall experience. Your images should be reviewed so that they are not set to height: auto. When this happens, the browser does not know specifically how to set the width and height until it must download the image, so it must process additional steps before applying the correct ratios, which causes the layout shifts to occur. However, if you serve images with different aspect ratios, then you need to set the srcset attribute, so that images render correctly on different devices.