htmlcssimageresponsive-imagessrcset

How to specify the width and height of an image while keeping it responsive at the same time?


While using srcset for responsive images, the code looks something like this:

<img 
src="dog.jpg" alt="a dog" 
srcset="dog-800.jpg 800w" 
sizes="(min-width:1000px) 800px, 80vw">

So, now when I am running lighthouse for that page, then it is saying that the image does not have width and height specified, which'll cause CLS.

Ok Understood, so now I have to specify the width and height... Now the code looks something like this:

<img 
src="dog.jpg" alt="a dog"
width="800px" height="440px" 
srcset="dog-800.jpg 800w" 
sizes="(min-width:1000px) 800px, 80vw">

But now, after specifying the width and height of this image, the srcset is not working (The specified width and height is overwriting my srcset rules).

So my question is how to specify width and height to this image along with keeping it responsive at the same time using srcset?

Thank you for your help.

For your reference I want to achieve something like this: Go to this page: https://web.dev/debug-web-vitals-in-the-field/ Then inspect the image on this page. See how they have specified the width and height and used srcset at the same time with the img tags.


Solution

  • I just got an answer to this problem. I fixed it by more observation and research. I thought to share it with others to help them if ever they encounter this. The final code for responsive image with width and height attribute will look like this:

    <img 
    src="dog.jpg" alt="a dog"
    width="800" height="440" 
    srcset="dog-800.jpg 800w" 
    sizes="(min-width:1000px) 800px, 80vw">
    

    I just removed the "px" from dimensions(width and height attribute) and that's it, it is working fine now.