使图像大小响应容器尺寸,同时保持其纵横比

问题描述 投票:0回答:1

我有一个最大高度的 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>

html css
1个回答
0
投票

也许用 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>

© www.soinside.com 2019 - 2024. All rights reserved.