0
votes

I used picture element for responsive images in different sizes per viewport a long time. it worked fine, but now I am forced to switch over to responsive <img> with srcset and sizes and I try to rewrite my picture element to the IMG-style.

After long searching I found good documentations at:

https://www.dofactory.com/html/img/sizes and more details at: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images

The code with picture was like this:

<picture>
    <source media="(max-width: 740px)" src="740.jpg" type="image/jpeg">
    <source media="(max-width: 980px)" src="1280.jpg" type="image/jpeg">
    <source media="(max-width: 1280px)" src="1600.jpg" type="image/jpeg">
    <source media="(max-width: 1480px)" src="1920.jpg" type="image/jpeg">
    <img src="740.jpg" title="..." alt="..." />
</picture>  

I re-wrote this to an responsive img like this:

<img src="740.jpg" title="..." alt="..." 
    srcset="
       740.jpg 740w,
       1280.jpg 1280w,
       1600.jpg 1600w,
       1920.jpg 1920w" 
    sizes="
       (max-width: 740px) 740px,
       (max-width: 980px) 1280px,
       (max-width: 1280px) 1600px,
       (max-width: 1480px) 1920px"
/>

This seems work wonderful on the first tests in browser. But then I noticed that on mobile devices it loads too big images.

The reason was the different pixel density of some mobile devices like explained at a-complete-guide-for-responsive-images

You can simulate this with dev-tools of firefox too: Firefox dev-tools

I tried to fix this with changing my code to

<img src="740.jpg" title="..." alt="..." 
    srcset="
       740.jpg 740w 1x,
       1280.jpg 1280w 1x,
       1600.jpg 1600w 1x,
       1920.jpg 1920w 1x" 
    sizes="
       (max-width: 740px) 740px,
       (max-width: 980px) 1280px,
       (max-width: 1280px) 1600px,
       (max-width: 1480px) 1920px"
/>

Does not work... (it always loads the smallest image for all viewpoints)

I tried the a solution without media queries in sizes from Handling responsive images with img srcset

Not working like I need it ...

So the big question is, how can I handle that the img-soureset solution works the same way like the picture Element:

In my example it should load:

  • 740.jpg for width 0-740
  • 1280.jpg for width 740-980
  • 1600.jpg for width 980-1600
  • 1920.jpg for everything bigger

And I DON`T want that it loads bigger images for devices with a bigger pixel density.

I know there are lots of similar questions in Stackoverflow, and I am searching for weeks for a working soluting, but nothing seems to work like expected, so I hope somebody can offer a solution