<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>
这是在Firefox中的结果:
这是在Chrome中显示的结果:
如您所见,在Firefox中,图像已经很好地缩小和调整了大小,因此所有图像都可以排成一行,而无需包裹或裁剪。在Chrome上,图像保持原始尺寸,这会导致在小窗口或div中裁剪。
这是预期的吗?难道我做错了什么?如何在Firefox和Chrome中获得相同的结果?
最佳答案
这些是flex容器中的初始设置:
flex-grow: 0
flex-shrink: 1
flex-basis: auto
简写为:
flex: 0 1 auto
因此,即使您没有在代码中指定这些规则,它们也适用于图像。
图像无法增长,它们可以缩小(大小足够避免容器溢出),并且最初将其大小调整为自然宽度(400px)。
这就是您在Firefox中看到的内容。图像正在缩小以很好地适合容器。
在Firefox中, flex 规则会覆盖图像的自然尺寸。
但是,在Chrome中,情况恰恰相反。图像的尺寸占主导。
简单的跨浏览器解决方案是将图像包装在另一个元素中,因此此新包装器将成为flex项,并采用默认的
flex: 0 1 auto
,无需覆盖任何内容。img {
width: 100%;
}
<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>
就哪种浏览器遵循规范指南而言,似乎是Firefox。在flex容器中,应遵循flex规则:
我说Firefox“似乎”是正确的,因为该规范说Flex规则应优先于CSS的
width
和height
属性。当然,在这种情况下,图像的尺寸未在CSS中定义。它们是图像的自然尺寸。因此,这种情况可能需要解释,并且Chrome可能不会违反任何准则。
但是,在另一种情况下,
height
属性是一个因素,Firefox坚持使用flex
,而Chrome坚持使用height
:Why is Firefox not honoring flexed div's height, but Chrome is?关于html - Firefox中的Flex会自动缩小图像,而Chrome中不会,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44521054/