我有几个列,我使用 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 - 为什么 object-fit 在 flexbox 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127384/