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

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

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

img {
  max-width: 500px;
}

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


当前回答

您可以创建如下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

其他回答

您可以创建如下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

您可以使用此选项:

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

您可以使用:-

transform: scaleX(1.2);

以改变宽度而不改变高度。

And

transform: scaleY(1.2);

更改高度而不更改宽度

您可以在html和css中的图像和视频标记上使用此选项。这也不会改变纵横比。

可以使用纵横比属性css

.my-image {
 aspect-ratio: 1/1; // square
 aspect-ratio: 16/9; // wide screen 1080p
 aspect-ratio: 4/3;
 aspect-ratio: 2/3;
}

Firefox 71+(2019-12-03)和Chrome 79+(2019-2-10)支持将IMG元素的宽度和高度HTML属性内部映射到新的纵横比CSS属性(该属性本身还不能直接使用)。

计算出的纵横比用于在加载图像之前为图像预留空间,只要计算出的宽高比等于图像的实际纵横比,就可以在加载图像后防止页面“跳转”。

要使其工作,必须通过CSS将两个图像维度之一覆盖为自动值:

IMG {max-width: 100%; height: auto; }
<img src="example.png" width="1280" height="720" alt="Example" />

在该示例中,即使图像尚未加载,并且作为最大宽度:100%的结果,有效图像宽度小于1280,也保持16:9(1280:720)的纵横比。

另请参阅相关的Firefox错误392261。