Vadim Hulevich
Vadim Hulevich

Reputation: 1833

Image elements do not have explicit width and height in Picture

PageSpeed Insights warning me:

Set an explicit width and height on image elements to reduce layout shifts and improve CLS.

But how I can fix it if I use Picture tag like this:

<picture>
    <source srcset="https://via.placeholder.com/150.webp" media="(max-width: 768px)" type="image/webp">
    <source srcset="https://via.placeholder.com/150.png x1, https://via.placeholder.com/300.png x2" media="(max-width: 768px)" type="image/png">
    <source srcset="https://via.placeholder.com/500.webp" type="image/webp">
    <source srcset="https://via.placeholder.com/500.png" type="image/png">
    <img src="https://via.placeholder.com/500.png">
</picture>

I don't need in mobile version image tag with width and height 500px. I want responsive image.

Of course i can set attributes width and height in image tag with value 500 and then use !import with @media in css, but i think it's just invalid rule.

How i can avoid this warning or fix it if it possible?

Upvotes: 8

Views: 3225

Answers (1)

Thurfir
Thurfir

Reputation: 125

This Pagespeed Insights message is misleading, you are NOT required to set the width + height of your images using the HTML attributes, you can also use CSS.

To be compliant with the rule in a <picture> you can either:

  • Set a width + height in CSS: .your-image { width: 200px; height: 150px; }

  • Set a width + aspect-ratio in CSS: .your-image { width: 100%; aspect-ratio: 16 / 10; }

  • Set a height + aspect-ratio in CSS: .your-image { height: 300px; aspect-ratio: 16 / 10; }

This CSS needs to be inlined or in a non-async/deffered file.

The width can be declared as percent in the CSS.

Source: https://github.com/GoogleChrome/lighthouse/issues/13098

Upvotes: 3

Related Questions