How To Fix "Image elements do not have explicit width and height"
PageSpeed Insights and Lighthouse audits will flag any "unsized" image with the message, "Image elements do not have explicit width and height."
So how do you fix it?
Generally, you need to add
height attributes to each
image so the browser knows its aspect ratio before loading it:
In this post, you'll learn how to fix an image failing this audit.
By default, browsers only allocate space for an image after it has downloaded its dimensions. Before that point, the image doesn't occupy any space on the page.
This becomes a problem if the browser renders a page before it knows the aspect ratio of an image in the viewport. Why? After the browser figures out the image's aspect ratio, it will allocate space for it by pushing down all the elements and text below it, causing a Cumulative Layout Shift (CLS).
You may have experienced annoying layout shifts when visiting websites with ads that load late and push down other elements on the page. Trying to read text or interact with an element that gets shifted, like a button, can be incredibly annoying. Layout shifts like these frustrate users.
Now, let's look at an example.
Let's start by running a PageSpeed Insights audit of this demo page, featuring an unsized image with some text below. What are the results?
- CLS: 0.223
- Total: 89
Get the image's dimensions in pixels and add
attributes to the image with these values. Make sure to not include
px unit. Because the image in the demo has a width of 704 px and
a height of 469 px, the HTML should look like the following:
And then add some CSS:
Alternatively, you can use the
CSS property instead of adding the
You can also apply
height attributes to images using the
<picture> element. For example, you could use the
serve different formats:
If the aspect ratio remains constant for all the
you don't need to add
height attributes to each one. But
if the aspect ratio changes, there is good
for that, too:
height, and CSS added, let's use PageSpeed
Insights to measure the impact of a
page after these changes:
- CLS: 0
- Total: 100
That's better! We've eliminated the Cumulative Layout Shift, and the page has a perfect score. Sometimes, minor CSS and HTML changes like these can go a long way in improving the user's experience.