[英]How do I use srcset and sizes in responsive HTML5 images for an image that's a percentage of it's container?
I'm confused by a few things in using the srcset
and sizes
attributes on an img
. 我被一些事情在使用混淆
srcset
和sizes
上的属性img
。 (I'm using picturefill but it follows the original spec) (我使用的是picturefill,但它遵循原始规范)
I have an image and on large screens, it's 25em
in width but on small phone-screens, it's 85%
of its container, not of the viewport. 我有一个图像,在大屏幕上,它的宽度为
25em
,但在小手机屏幕上,它是其容器( 而不是视口)的85%
。 I do not want to give it a set size on smaller screens - instead I want it to adapt to its container (which is a div
). 我不想给它在小屏幕上设置大小-相反,我希望它适应它的容器(这是一个
div
)。 I cannot figure out how to do this. 我不知道该怎么做。
I also am not happy that I have to hardcode sizes and media queries into the HTML instead of putting them in CSS - it puts the same information in two places. 我也很高兴我必须将大小和媒体查询硬编码到HTML中,而不是将它们放在CSS中-它会将相同的信息放在两个地方。 Is there a way around this?
有没有解决的办法?
What I have: 我有的:
<!--
Is there any way to make the sizes be percentages of the container?
-->
<img
sizes="(min-width: 1000px) 750px, (min-width: 200px) 50vw"
srcset="images/full_0.png 750w, images/small_0.png 187w"
alt="Sizing">
What I want: 我想要的是:
<!--
The "use-750w" tells it which image to load but NOT the size
to make it. Instead, it lets CSS size the image.
-->
<img
sizes="(min-width: 1000px) use-750w, (min-width: 200px) use-187w"
srcset="images/full_0.png 750w, images/small_0.png 187w"
alt="Sizing">
You can't because the HTML is separated from the CSS and the browser must know the image size before the CSS is loaded. 您不能这样做,因为HTML与CSS分离,并且浏览器必须在加载CSS之前知道图像大小。 Therefore the browser does not know the width of your
div
. 因此,浏览器不知道
div
的宽度。
You can give lazysizes a try. 您可以尝试lazysizes 。 In this case all image width must be computable before the image is loaded via CSS.
在这种情况下,在通过CSS加载图像之前,所有图像宽度都必须是可计算的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.