Fix for Image elements have explicit width and height

When you are testing a website in google page sight or lighthouse, You can use 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 causes a bad experience.

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

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

Browsers will not understand the width and height if you don’t specify height and width, It causes cumulative layout shift.

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

Add width and height attributes with pixel to img tag

Add width and height attributes to the 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;
}