Fix for Image elements have explicit width and height


When you are testing an website in google page sight or lighthouse, You can se Cumulative Layout Shift score is high when you don’t specify the image dimensions.

If you don’t specify the width and height for an image, The page loading shifts the next and causing an bad experience

Here is an error Image elements do not have explicit width and height

This error occurs for an image not defined the fixed width and height for img tag.

Browsers will not understand the width and height if you don’t specified height and width, This causes cumulative layout shift

There are multiple ways to fix width and height attributes to img tag

Add width and height attributes with pixel to img tag

Add width and height attributes to img tag with pixel values

<img width="500" height="200" src="image.png"/>

With CSS,

We can easily add the following attributes using css code

img {
  max-width: 100%;
  height: auto;
    aspect-ratio: 16/9;

}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.