我在100 * 300px的div内有一个240 * 240px的图像(演示值,实际值各不相同,并且未知)。我使用object-fit: contain使图像在div内完全可见,并保持其宽高比。问题在于object-fit不会修改图像的宽度,从而导致奇怪的“填充”(可以这么说)。

html - 为什么对象适合不会影响宽度或高度?-LMLPHP

如何使图像仅占据所需的宽度,而不是原始宽度?

演示: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属性通常与widthheightmax-widthmax-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

09-26 19:56
查看更多