Image elements do not have explicit width and height in Picture
Asked Answered
C

1

8

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?

Cumuliform answered 3/4, 2021 at 7:56 Comment(3)
I have the exact same question and I haven't found a reasonable answer to this. We would need to be able to add "width" and "height" attributes to the source elementCorniculate
Have you found solution for that?Gavriella
@Corniculate You can add width and height attributes to source element. Morden browsers support this and this is also in the current HTML 5 spec.Weiland
A
3

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

Analiese answered 27/9, 2021 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.