css - 为什么 img 宽度在某些浏览器中的结果不同?谁是正确的?

标签 css google-chrome internet-explorer firefox

这有一个演示:

<div style="position:absolute;">
   <img
      src="https://i.imgur.com/iQ2rVup.jpg"
      style="width:100%;height:100px;"
   />
</div>

On Codepen

Chrome 结果:

Firefox/IE 结果:

我看到了W3C文档。
绝对定位非位移元素计算如下。

min(max(preferred minimum width, available width), preferred width)  

https://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width

难道chrome的结果不对?

最佳答案

这可能不会回答问题,但我会尝试解释 chrome 发生了什么以及为什么两者都是正确的。

首先,您应该注意到即使您考虑 inline-block 元素或 float 也会发生同样的情况,因为它们也是收缩以适合元素

<div style="display:inline-block;">
   <img
      src="https://i.imgur.com/iQ2rVup.jpg"
      style="width:100%;height:100px;"
   />
</div>
<br>
<div style="float:left;">
   <img
      src="https://i.imgur.com/iQ2rVup.jpg"
      style="width:100%;height:100px;"
   />
</div>

现在都是关于 width:100% 的。由于它是一个百分比值,因此引用将是包含 block 的宽度,但我们的包含 block 是一个缩小到适合的元素,这意味着它的宽度取决于它的内容。这里我们有一种循环。

这是the specification的一部分描述这种行为的:

Sometimes the size of a percentage-sized box’s containing block depends on the intrinsic size contribution of the box itself, creating a cyclic dependency. When calculating the containing block’s size, the percentage behaves as auto. Then, unless otherwise specified, when calculating the used sizes and positions of the containing block’s contents: ...

所以基本上,我们将图像的宽度视为 auto,我们计算 div(父元素)的宽度,然后我们使用 width :100% 再次计算宽度。

区别来了。 Firefox 正在考虑在计算中为图像设置的高度,以找到图像宽度的值(如 the specification 的这一部分所述)。现在我们有了图像的宽度,父元素将收缩以适应这个宽度,我们将根据之前的内容再次重新考虑width:100%宽度。

Chrome 正在将宽度设置为自动,但没有考虑高度,在这种情况下,宽度将使用图像的固有尺寸具有以下内容:

<div style="display:inline-block;">
   <img
      src="https://i.imgur.com/iQ2rVup.jpg"
      style="/*width:100%;height:100px;*/"
   />
</div>

现在我们有了新的宽度,我们可以计算父元素的宽度(收缩以适合),现在如果我们设置width:100%;height:100px 到图像,我们将有 100px 高度和 100% 包含 block 宽度,这是初始图像宽度。


现在的问题是:当这张图片被认为是 auto 时,我们是否应该考虑高度来计算图像的 new 宽度值,以便计算宽度包含 block ?如果没有 Chrome 是正确的,如果是,Firefox 是正确的。


值得注意的是,在这两种情况下,图像都可能会失真。在实际示例中,我们在 Firefox 上没有注意到这一点,因为高度很小。

这是一个动画来说明失真并显示两种浏览器之间的不同行为。

img {
 width:100%;
 height:200px;
}

.wrapper {
 border:2px solid;
 animation:change 5s linear infinite alternate;
}

.wrapper > div {
  border:2px solid green;
}

@keyframes change {
  from {
    width:500px;
  }
  to {
    width:100px;
  }

}
<div class="wrapper">
  <div style="display:inline-block;">
    <img src="https://i.imgur.com/iQ2rVup.jpg"  />
  </div>
</div>

这里的wrapper 用作我们收缩以适应元素的包含 block ,并将定义可用宽度。我们可以清楚地看到,在 Chrome 中图像总是失真,而在 Firefix 中失真会稍后发生。

关于css - 为什么 img 宽度在某些浏览器中的结果不同?谁是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55949254/

相关文章:

css - 为什么我的容器/包装器的背景没有延伸到所有内容后面

css - Chrome 突然覆盖样式表

javascript - 当 method=get 且 URL 包含散列时,使用 Javascript 更改表单操作时 IE 中的错误

DIV top 属性的 CSS 跨浏览器问题

css - IE 不在表格单元格中居中文本

jquery - 为 Jquery 可排序 Portlet 添加最大化和最小化按钮

jquery - 改进占位符

html - IE8圆 Angular ,部分div溢出到其他div不可见

javascript - 为什么没有在 Chrome 中验证美国运通卡?

javascript - 为什么我不能使用 Chrome 的 "Inspect Element"修改此代码中的 Javascript?