首页 > 解决方案 > 如何使用 CSS 调整图像大小以适合其容器

问题描述

我想制作具有恒定宽度和高度的 div,其中包含大小未知的子图像。

像这样的东西:

我得到的最接近的是 withmax-height: inherit; max-width: inherit但它改变了纵横比

.parent {
  border: 1px solid ;
  width: 40vh;
  height: 40vh;
  overflow: hidden;
  display: flex;
}

img {
  max-width: inherit;
  max-height: inherit;
  height: inherit;
  width: inherit;
}
<div class="parent">
  <img src="https://images.pexels.com/photos/1123982/pexels-photo-1123982.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" />
</div>

我怎么能做到这一点?

标签: htmlcss

解决方案


您需要使用object-fit:covercss 属性imgvideo应该调整其大小以适合其容器。

运行下面的代码片段。

.parent {
  border: 1px solid;
  width: 20vh;
  height: 20vh;
  overflow: hidden;
  display: flex;
}

img {
  max-width: inherit;
  max-height: inherit;
  height: inherit;
  width: inherit;
  object-fit: cover;
}
<div class="parent">
  <img src="https://images.pexels.com/photos/1123982/pexels-photo-1123982.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" />
</div>


推荐阅读