html - 为什么对象适配在 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 - 为什么对象适配在 Flexbox 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39437612/

相关文章:

html - 为 wordpress 主题创建一个圆形 css

javascript - SimplyScroll 在此页面上中断

PHP 文件作为 URL 失败视频流

html - 如何将标题放在图像下方的一行中?

javascript - angularJS - 背景图片不见了

css - Drupal 将类添加到特定于节点类型的行

html - 如何让DIV的宽度取决于它的内容然后居中对齐?

css - 我怎样才能让一个 flex 盒子的 child 继承高度

html - CSS flex : Display like rowspan and colspan

javascript - Jquery循环遍历表中的所有行,没有第一行