在 Safari 的 flexbox 中拉伸图像

新手上路,请多包涵

这只是 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 许可协议

阅读 1.1k
2 个回答

这显然是一个错误。

align-items 属性 的默认设置是 stretch 。大多数主流浏览器都会明智地处理这个问题,将图像拉伸 _到容器的范围内_。

无论出于何种原因,Safari 都会将图像拉伸到其自然高度,并随身携带容器。


flex-direction: row

要解决此问题,请在 align-items 属性中使用 flex-start 覆盖 stretch 默认值。

 .container {
  display: flex;
  flex-direction: column;
}
.container section:first-child {
  display: flex;
  align-items: flex-start; /* new */
  margin-bottom: 25px;
}
.container img {
  width: 125px;
  height: auto;
}
 <div class="container">
  <section>
    <img src="http://i.imgur.com/60PVLis.png">
  </section>
  <section>
    <img src="http://i.imgur.com/60PVLis.png">
  </section>
</div>

jsFiddle 演示


flex-direction: column

将 flex 容器的方向切换为 column 也可以解决问题。这是因为 align-items 现在适用于宽度 ,并且 您已经在图像上定义了宽度。

如果您将图像尺寸从

.container img {
   width: 125px;
   height: auto;
}

.container img {
   width: auto;
   height: 125px;
}

…您在 Safari 中会遇到与 flex-direction: row 相同的问题,并且需要 align-items: flex-start 进行更正。

 .container {
  display: flex;
  flex-direction: column;
}

.container section:first-child {
  display: flex;
  /* align-items: flex-start; */
  margin-bottom: 25px;
}

.container img {
  width: auto;
  height: 125px;
}
 <div class="container">
  <section>
    <img src="http://i.imgur.com/60PVLis.png">
  </section>
  <section>
    <img src="http://i.imgur.com/60PVLis.png">
  </section>
</div>

jsFiddle 演示

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 4.0 许可协议

对我来说,这两种解决方案都不起作用。我已经有了 flex-direction: columnaligh-items: center ,尽管在我的例子中,我在同一个弹性容器中还有一些其他元素,除了图像。不确定它是否有任何影响。

在我的案例中,实际解决问题的方法只是用 div 包装图像:

 <section>
    <div>
        <img src="https://via.placeholder.com/250">
    </div>
</section>

原文由 eOf 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题