问题描述
我目前正在尝试在我的网站上制作更好的响应式图片.经过一番研究,我发现了 srcset
和 sizes
属性.
I am currently trying to make better responsive images on my site. After some research I found the the srcset
and sizes
attributes.
我的目标如下:
- 当屏幕尺寸大于 600 像素或小于 300 像素时,我想提供 250x250 的图片
- 当它介于这两个值之间时,我想提供 350x350 的图像
- 此外,我希望为具有更高像素比的屏幕提供更高分辨率的图像
这是我想出来的.但它不像我想的那样工作.始终提供 250x250 的小型广告.
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?
推荐答案
好的.经过一番细致的研究,我发现我没有正确理解 sizes
属性.
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" />
这篇关于img srcset 和尺寸无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!