html - 为什么 object-fit 不影响宽度或高度?

标签 html css flexbox

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

enter image description here

如何让图片只占用所需的宽度,而不是占用原始宽度?

演示: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-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/

相关文章:

python - 数据抓取器 : the contents of the div tag is empty (? ?)

javascript - jQuery 图像幻灯片无法正常工作

javascript - 让脉冲 SVG 在 IE 中工作

css - Bootstrap + CSS : How to set a div's height according to its width?

html - 如何在表格的正中心显示图像?

javascript - 2 个翻转部分的动画侧边菜单

html - 在 Bootstrap 中将无序列表居中在容器流体中

html - 省略号溢出会破坏 flex 的 child 尺寸

css - Le bootstrap 入门模板

css - 合适的 CSS 显示每行显示 3 个元素,行数任意?