Firefox中的Flex会自动缩小图像,但不能在Chrome中缩小图像

Fli*_*imm 5 html css css3 flexbox

<h1>Window width:</h1>

<div style="display: flex">
  <img src="https://unsplash.it/400/225?image=10" alt="1">
  <img src="https://unsplash.it/400/225?image=11" alt="2">
  <img src="https://unsplash.it/400/225?image=12" alt="3">
</div>

<h1>Wrapped in 500px wide div:</h1>

<div style="width: 500px; overflow: auto">
  <div style="display: flex">
    <img src="https://unsplash.it/400/225?image=10" alt="1">
    <img src="https://unsplash.it/400/225?image=11" alt="2">
    <img src="https://unsplash.it/400/225?image=12" alt="3">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这就是Firefox中的结果:

Firefox 53中页面的屏幕截图

这就是Chrome中的结果:

Chrome 59中页面的屏幕截图

正如您所看到的,在Firefox中,图像已经很好地缩小和调整大小,因此所有图像都适合一行而不包装或裁剪.在Chrome上,图像保持原始大小,导致小窗口或div中的裁剪.

这是预期的吗?难道我做错了什么?如何在Firefox和Chrome中获得相同的结果?

Mic*_*l_B 9

这些是flex容器中的初始设置:

  • flex-grow: 0
  • flex-shrink: 1
  • flex-basis: auto

简写是:

  • flex: 0 1 auto

因此,即使您未在代码中指定这些规则,它们也适用于图像.

图像不能生长,它们可以收缩(同样且足以避免溢出容器),并且它们最初的尺寸为其自然宽度(400px).

这就是你在Firefox中看到的.图像正在缩小以适应容器内部.

在Firefox中,弹性规则覆盖了图像的自然尺寸.

然而,在Chrome中,情况恰恰相反.图像的尺寸是普遍的.

简单的跨浏览器解决方案是将图像包装在另一个元素中,因此这个新的包装器成为flex项并采用默认值flex: 0 1 auto,并且不需要覆盖任何内容.

img {
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Window width:</h1>

<div style="display: flex">
  <span><img src="https://unsplash.it/400/225?image=10" alt="1"></span>
  <span><img src="https://unsplash.it/400/225?image=11" alt="2"></span>
  <span><img src="https://unsplash.it/400/225?image=12" alt="3"></span>
</div>

<h1>Wrapped in 500px wide div:</h1>

<div style="width: 500px; overflow: auto">
  <div style="display: flex">
    <span><img src="https://unsplash.it/400/225?image=10" alt="1"></span>
    <span><img src="https://unsplash.it/400/225?image=11" alt="2"></span>
    <span><img src="https://unsplash.it/400/225?image=12" alt="3"></span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

就浏览器遵守规范指南而言,它似乎是Firefox.在flex容器中,应以flex规则为准:

7.1.该flex 速记

如果框是弹性项目,flex则参考而不是主要大小属性来确定框的主要大小.

flex项的main size属性widthor height属性.

我说Firefox"看起来"是正确的,因为规范说灵活规则应优先于CSS widthheight属性.

当然,在这种情况下图像的尺寸没有在CSS中定义.它们是图像的自然维度.因此,这种情况可能会被解释,Chrome可能不会违反任何准则.

然而,在另一个场景中,height属性是一个因素,Firefox坚持flex,而Chrome 坚持height:为什么Firefox不尊重屈曲div的高度,但Chrome是?