我在100 * 300px的div内有一个240 * 240px的图像(演示值,实际值各不相同,并且未知)。我使用object-fit: contain
使图像在div内完全可见,并保持其宽高比。问题在于object-fit
不会修改图像的宽度,从而导致奇怪的“填充”(可以这么说)。
如何使图像仅占据所需的宽度,而不是原始宽度?
演示:http://codepen.io/alexandernst/pen/ONvqzN
.wrapper {
height: 100px;
width: 300px;
border: 1px solid black;
}
.flex {
display: flex;
}
img {
object-fit: contain;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
最佳答案
object-fit
属性通常与width
,height
,max-width
和max-height
一起使用。例子:
.wrapper {
height: 100px;
width: 300px;
border: 1px solid black;
}
.flex {
display: flex;
}
img {
object-fit: contain;
height: 100%;
width: auto;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
实际上,即使没有
object-fit
,它也可以正常工作,请参阅此jsFiddle。