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

标签 html css 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>

图像未调整大小,如 this demo 中所示.这是为什么?

最佳答案

来自specification :

The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

关键术语是:适合由其使用的高度和宽度建立的盒子

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

因此,废弃容器并使图像本身成为 flex 元素。

.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>

Revised Codepen


其他详细信息

5.5. Sizing Objects: the object-fit property

The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

Here are three of the values:

  • cover

    The replaced content is sized to maintain its aspect ratio while filling the element's entire content box.

  • contain

    The replaced content is sized to maintain its aspect ratio while fitting within the element's content box.

  • fill

    The replaced content is sized to fill the element's content box.

使用cover 图像保持其宽高比并覆盖所有可用空间。使用此选项,大部分图像可能会被裁剪到屏幕外。

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

使用 fill 时,纵横比被放弃,图像的大小适合盒子。


浏览器兼容性

在撰写本文时,object-fit is not supported by Internet Explorer .有关解决方法,请参阅:

关于html - 为什么 object-fit 在 flexbox 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127384/

相关文章:

javascript - 如何使用 ondrop 事件访问类元素内的段落元素并将其删除?

javascript - 在确认对话框取消选择后,如何取消用户单选按钮选择?

html - 将导航栏完全左对齐并分成 12 个部分

html - div 在 chrome 和 safari 中定位不正确

html - 如何使以下输入区域扩展到屏幕末尾?

html - 如何对齐双列布局中的第二列?

php打开电子邮件客户端

javascript - 当屏幕达到一定尺寸时使用 jQuery 或 javascript 删除 Div 标签?

css - 如何创建具有相等间距/框宽度的自动流体网格?

javascript - 在 flex-box 中为动态添加的 flex-item 添加一个按钮