html - 如何使用 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>
我怎么能做到这一点?
解决方案
您需要使用object-fit:cover
css 属性img
或video
应该调整其大小以适合其容器。
运行下面的代码片段。
.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>
推荐阅读
- python - 如何在虚拟环境中使用 conda?
- c++ - c 和 c++ 中奇怪的类似函数的语法
- apache-spark - 使用 Spark Cassandra 连接器的不同方式
- c - 使用正则表达式在 C 中设置正确的正则表达式的问题
- themes - 如何使用 NativeScript 主题 v3 设置背景颜色
- postgresql - lo_import 的权限被拒绝
- c# - 使用 NEST 库查询 ElasticSearch 服务器时如何应用多个条件?
- java - 如何使用 Spring Security 与节点身份验证服务器通信来保护 Java REST API(内部使用 AWS cognito)
- mysql - 从多个sql表中查询数据
- c++ - 如何检查使用的 c++ 编译器 VS 2019 的版本?