我在 100*300 像素的 div 中有一个 240*240 像素的图像(演示值,实际值各不相同且未知)。我使用 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
和 一起使用>最大高度
。示例:
.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 .
关于html - 为什么 object-fit 不影响宽度或高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636754/