我有一个最大高度的 div。它包含一个具有纵向纵横比的图像。我的目标是,图像应该适应容器的大小(最大高度和最大宽度),而不会失去它的纵横比。
当我在图像上使用
height: auto; width: 100%
时,图像变得比它的父母max-height
.
另一方面,如果我在图像上设置
width: auto; height: 100%
,它会变得比它的父母宽度更大。
如果我设置
max-height: 50px; width: 100%;
它可能会扭曲,这取决于它的父母宽度。
.container {
max-height: 50px;
border: 2px solid red;
}
img {
width: 100%;
height: auto
}
<div class="container">
<img src="https://placehold.co/40x60" width="40" height="60"/>
</div>
也许用 CSS 网格
.container {
max-height: 50px;
border: 2px solid red;
display: grid;
place-content: center;
grid-template-rows: 100%;
/* for the demo */
overflow: hidden;
resize: auto;
}
img {
max-height: 100%;
max-width: 100%;
margin: auto;
}
<div class="container">
<img src="https://placehold.co/40x60" width="40" height="60"/>
</div>