img srcset and sizes not working as I would expect

主宰稳场 提交于 2021-02-04 21:44:31

问题


I am currently trying to make better responsive images on my site. After some research I found the the srcset and sizes attributes.

My goal here is the following:

  • When the screen size is above 600px or below 300px I want to serve a 250x250 image
  • When it is between these two values I want to serve a 350x350 image
  • Also I want higher resolution images for screens which have a higher pixel ratio

This is what I came up with. But it is not working as I though it would. The small 250x250 is always being served.

<img src="https://placehold.it/250"
  srcset="https://placehold.it/700 700w, https://placehold.it/500 500w, https://placehold.it/350 350w, https://placehold.it/250 250w"
   sizes="((max-width: 600px) and (min-width: 300px) and (min-resolution: 2)) 350px, (min-resolution: 2) 250px, ((max-width: 600px) and (min-width: 300px)) 350px, 250px" />

And I have one additional question:
In my tests I found out that the browser won't load new images when the window is resized so that a different image should be served. Is it possible to do that?


回答1:


Ok. After some tidious research I found out that I did not understand the sizes-attribute correctly.

The following is how I can achieve what I want:

<img src="https://placehold.it/250"
  srcset="https://placehold.it/700 700w, https://placehold.it/500 500w, https://placehold.it/350 350w, https://placehold.it/250 250w"
   sizes="(max-width: 600px) calc(100vw - 50px), 250px" />


来源:https://stackoverflow.com/questions/31599363/img-srcset-and-sizes-not-working-as-i-would-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!