图像渲染尺寸超过最大宽度

发布于 2025-01-25 16:39:24 字数 513 浏览 1 评论 0原文

我有一个响应式IMG标签:

<img width='800' height='600' srcset='img-400px.jpg 400w, img-700px.jpg 700w, img-1000px.jpg 1000w' sizes='(max-width: 1024px) 100vw, (max-width: 1840px) 63vw, 1200px' src='img.jpg'>

和CSS规则:

object-fit: contain;
width: auto;
margin: auto;
height: auto;
max-height: 900px;
max-width: 100%;

即使原始图像宽度为800px,并且我的规则最大宽度:100%浏览器浏览器的图像比800px更宽。如果我删除宽度:auto,则渲染尺寸是正确的(最大800px)。为什么宽度:自动更改行为?

I have a responsive img tag:

<img width='800' height='600' srcset='img-400px.jpg 400w, img-700px.jpg 700w, img-1000px.jpg 1000w' sizes='(max-width: 1024px) 100vw, (max-width: 1840px) 63vw, 1200px' src='img.jpg'>

And CSS rules:

object-fit: contain;
width: auto;
margin: auto;
height: auto;
max-height: 900px;
max-width: 100%;

Even though the original image width is 800px and I have the rule max-width: 100% the browser renders the image wider than 800px. If I remove width: auto, the rendered size is correct (max 800px). Why does width: auto change the behaviour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无尽的现实 2025-02-01 16:39:24

我想了解问题是什么。

浏览器不会覆盖max Width设置。当我将IMG大小属性与CSS Rule width一起使用时,浏览器使用大小来分配空间对于图像。这个空间可以比图像的真实宽度宽。当我删除宽度:auto规则时,浏览器从IMG的宽度属性中获取宽度信息,并且图像不能超过其内在维度。因此,解决方案是删除宽度:auto规则。

I figured to understand what is the issue.

The browser does not override the max-width setting. When I use img with sizes attribute together with css rule width: auto, the browser uses sizes to allocate space for the image. This space can be wider than the image's real width. When I remove width: auto rule, the browser takes the width information from img's width attribute and the image can't exceed its intrinsic dimension. So the solution was to remove width: auto rule.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文