我有几个列,我使用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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
图像没有调整大小,如本演示中所示.这是为什么?
Mic*_*l_B 28
从规格:
该
object-fit
属性指定如何将替换元素的内容拟合到由其使用的高度和宽度建立的框中.
关键术语是:安装在由其使用的高度和宽度确定的盒子上
图像被替换,而不是其容器.由其使用的高度和宽度建立的盒子与图像本身有关,而不是与容器有关.
因此,废弃容器并使图像本身成为弹性项目.
.container {
display: flex;
flex-direction: row;
width: 100%;
}
img {
object-fit: cover;
flex: 1;
margin-right: 1rem;
overflow: hidden;
height: 400px;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
该
object-fit
属性指定如何将替换元素的内容拟合到由其使用的高度和宽度建立的框中.以下是三个值:
cover
替换的内容的大小可以在填充元素的整个内容框时保持其宽高比.
contain
替换的内容的大小可以在适合元素的内容框时保持其宽高比.
fill
替换的内容大小适合填充元素的内容框.
与cover
所述图像保持其宽高比,并覆盖所有可用空间.使用此选项,可以在屏幕外裁剪大部分图像.
随着contain
纵横比也保持,但图像进行缩放以适应箱内.这可能会导致左侧和/或右侧(纵向拟合)或顶部和/或底部(横向拟合)出现空白.该object-position
属性可用于在其框内移动图像.
随着fill
纵横比被放弃,所述图像的尺寸适合的框.
浏览器兼容性
在撰写本文时,object-fit
Internet Explorer不支持.有关解决方法,请参阅:
object-fit
Edge(和其他浏览器)上CSS 回退的巧妙技巧object-fit
Internet Explorer 的polyfillobject-fit
在IE9,IE10,IE11,Edge和其他旧浏览器上添加支持object-fit
属性的Polyfill(主要是IE)将图像填入/装入容器中.Ori*_*iol 14
问题是object-fit
指定如何在图像内部绘制图像img
,但是您没有指定这些元素的大小,只指定了.test
父项的大小.
所以Michael_B的答案的替代方案是使图像与flex项目具有相同的大小:
img {
height: 100%;
width: 100%;
object-fit: cover;
}
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)