问题
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