这只是 Safari 中的一个问题,对我来说看起来像是一个 Safari 错误。这是该问题的简化版本的 小提琴。
当图像位于设置了宽度且 height: auto
的嵌套弹性框元素中时,它正在被拉伸……自动高度不起作用。是否需要添加一些额外的东西才能在 Safari 中工作?
.container {
display: flex;
flex-direction: column;
}
.container section:first-child {
display: flex;
margin-bottom: 25px;
}
.container img {
width: 125px;
height: auto;
}
<div class="container">
<section>
<img src="https://via.placeholder.com/250">
</section>
<section>
<img src="https://via.placeholder.com/150">
</section>
</div>
我希望图像的高度会自动调整以保持纵横比。这适用于除 Safari 之外的所有浏览器。在 Safari 中,图像被拉伸并且自动高度不起作用。
原文由 Brian 发布,翻译遵循 CC BY-SA 4.0 许可协议
这显然是一个错误。
align-items
属性 的默认设置是stretch
。大多数主流浏览器都会明智地处理这个问题,将图像拉伸 _到容器的范围内_。无论出于何种原因,Safari 都会将图像拉伸到其自然高度,并随身携带容器。
flex-direction: row
要解决此问题,请在
align-items
属性中使用flex-start
覆盖stretch
默认值。jsFiddle 演示
flex-direction: column
将 flex 容器的方向切换为
column
也可以解决问题。这是因为align-items
现在适用于宽度 ,并且 您已经在图像上定义了宽度。如果您将图像尺寸从
至
…您在 Safari 中会遇到与
flex-direction: row
相同的问题,并且需要align-items: flex-start
进行更正。jsFiddle 演示