我正在处理图像,我遇到了纵横比问题。

<img src="big_image.jpg" width="900" height="600" alt="" />

如您所见,高度和宽度已经指定。我为图像添加了CSS规则:

img {
  max-width: 500px;
}

但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。


当前回答

如果应用程序可以具有任何纵横比或分辨率的图像,则可以像此链接中那样管理高度和宽度。

这使用Javascript和HTML

https://stackoverflow.com/a/65090175/13338731

其他回答

只需将此添加到css中,它将自动收缩和扩展,并保持原始比例。

img {
    display: block;
    max-width: 100%;
    max-height: 100%;
    width: auto;
    height: auto;
}

这是精神上的。使用比例缩小属性-它可以自行解释。

内联样式:

<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />

这将阻止flex拉伸它。在这种情况下,图像将达到其父容器宽度的50%,并且高度将缩小以匹配。

保持简单。

国际货币基金组织{显示:块;最大宽度:230px;最大高度:95px;宽度:自动;高度:自动;}<p>此图像最初为400x400像素,但应通过CSS调整大小:</p><img width=“400”height=“400”src=“http://i.stack.imgur.com/aEEkn.png">

如果图像对于指定区域太大,这将使图像收缩(作为缺点,它不会放大图像)。

您可以使用此选项:

img { 
    width: 500px; 
    height: 600px; 
    object-fit: contain; 
    position: relative; 
    top: 50%; 
    transform: translateY(-50%); 
}

您可以创建如下div:

<div class="image" style="background-image:url('/to/your/image')"></div>

并使用此css设置其样式:

height: 100%;
width: 100%;
background-position: center center;
background-repeat: no-repeat;
background-size: contain; // this can also be cover