为什么 object-fit 在 flexbox 中不起作用?

新手上路,请多包涵

我有几列,我使用 flex 赋予它们相同的宽度。每个包含 img 标签,我希望这些图像显示 object-fit: cover 尺寸。

 .container {
  display: flex;
  flex-direction: row;
  width: 100%;
}
.test {
  flex: 1;
  margin-right: 1rem;
  overflow: hidden;
  height: 400px;
}
img {
  object-fit: cover;
}
 <div class="container">
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
</div>

图像没有调整大小,如 本演示 所示。这是为什么?

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

阅读 1.6k
2 个回答

规格

object-fit 属性指定替换元素的内容应如何适应由其使用的高度和宽度建立的框。

关键术语是: 安装到由其使用的高度和宽度建立的盒子

图像被替换,而不是它的容器。并且其使用的高度和宽度所建立的框与图像本身有关,而不是其容器。

因此,废弃容器并使图像本身成为弹性项目。

 .container {
  display: flex;
  flex-direction: row;
  width: 100%;
}

img {
  object-fit: cover;
  flex: 1;
  margin-right: 1rem;
  overflow: hidden;
  height: 400px;
}
 <div class="container">
  <img src="http://placehold.it/1920x1080">
  <img src="http://placehold.it/1920x1080">
  <img src="http://placehold.it/1920x1080">
  <img src="http://placehold.it/1920x1080">
</div>

修改后的代码笔


额外细节

5.5.调整对象大小: object-fit 属性

object-fit 属性指定替换元素的内容应如何适应由其使用的高度和宽度建立的框。

以下是其中三个值:

  • cover

替换内容的大小会在填充元素的整个内容框时保持其纵横比。

  • contain

替换内容的大小在适合元素内容框的同时保持其纵横比。

  • fill

替换内容的大小会填充元素的内容框。

使用 cover 图像保留其纵横比并覆盖所有可用空间。使用此选项,可以在屏幕外裁剪大部分图像。

使用 contain 纵横比也保持不变,但图像缩放以适合框内。这可能会导致左侧和/或右侧(纵向适合)或顶部和/或底部(横向适合)出现空白。 object-position 属性可用于在其框内移动图像。

使用 fill 宽高比被放弃,图像的大小适合盒子。


浏览器兼容性

在撰写本文时, Internet Explorer 不支持 object-fit 。有关解决方法,请参阅:

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

问题是 object-fit 指定如何在 img 中绘制图像,但您没有指定这些元素的大小,仅指定它们的大小 .test 父母。

因此,替代 Michael_B 的答案 是使图像与 flex 项目具有相同的大小:

 img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

 .container {
  display: flex;
  flex-direction: row;
  width: 100%;
}
.test {
  flex: 1;
  margin-right: 1rem;
  overflow: hidden;
  height: 400px;
}
img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}
 <div class="container">
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
  <div class="test"><img src="http://placehold.it/1920x1080"></div>
</div>

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

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