我有几列使用 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>
其他详细信息
5.5. Sizing Objects: the
object-fit
propertyThe
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 。有关解决方法,请参阅:
- Neat trick for CSS
object-fit
fallback on Edge (and other browsers) - fitie - An
object-fit
polyfill for Internet Explorer - object-fit-images - Adds support for
object-fit
on IE9, IE10, IE11, Edge and other old browsers - Polyfill (mostly IE) for CSS
object-fit
property to fill-in/fit-in images into containers.
关于html - 为什么对象适配在 Flexbox 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39437612/