Neil Nand
Neil Nand

Reputation: 559

Cannot get srcset to load correct image

I'm using the HTML below & testing using Chrome but no matter the width of the browser (when using the responsive dev tools) the 150x150 image is always loaded. If I was understanding it correctly I thought when the browser width is under 150px it would load the 60x60 image?

<a href="/">
  <img src="https://dummyimage.com/60x60/000/fff" 
    sizes="100vw" 
    srcset="https://dummyimage.com/150x150/000/fff 150w">
</a>

Upvotes: 0

Views: 264

Answers (1)

Nicolas Hoizey
Nicolas Hoizey

Reputation: 2031

It always loads the 150px image because that's the only one you list in the srcset attribute.

Here is what you should do:

<img
  src="https://dummyimage.com/60x60/000/fff" 
  sizes="100vw"
  srcset="https://dummyimage.com/60x60/000/fff 60w,
          https://dummyimage.com/150x150/000/fff 150w">

The browser will then load the 60px image if the full viewport (100vw in the sizes attribute) is somewhere between 60 and 150px, closer to 60 than 150, depending on browsers implementations.

If the viewport is 61px, it would make no sense to load the really bigger 150px image, so the 60px should be downloaded.

But if the viewport is 149px, the enlarged 60px image would look ugly, so the 150px one should be downloaded.

That's at least how is is implemented in Chrome.

Upvotes: 1

Related Questions