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

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

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

img {
  max-width: 500px;
}

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


当前回答

将图像容器标记的CSS类设置为图像类:

<div class="image-full"></div>

并将其添加到CSS样式表中。

.image-full {
    background: url(...some image...) no-repeat;
    background-size: cover;
    background-position: center center;
}

其他回答

要强制图像符合精确的大小,您不需要编写太多代码。太简单了

国际货币基金组织{宽度:200px;高度:自动;对象拟合:包含;/*按图像大小调整徽标*/-o-object-fit:contain;/*为opera浏览器安装徽标*/对象位置:顶部;/*设置徽标位置*/-o对象位置:顶部;/*opera浏览器的徽标位置*/}<img src=“http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png“alt=”徽标“>

将图像容器标记的CSS类设置为图像类:

<div class="image-full"></div>

并将其添加到CSS样式表中。

.image-full {
    background: url(...some image...) no-repeat;
    background-size: cover;
    background-position: center center;
}

删除“height”属性。

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

通过指定这两个选项,可以更改图像的纵横比。只需设置一个即可调整大小,但保持纵横比。

(可选)限制过大:

<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>

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。

您可以使用此选项:

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