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

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

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

img {
  max-width: 500px;
}

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


当前回答

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

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

其他回答

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

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

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

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

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

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

删除“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;"/>

与这里的一些答案非常相似,但在我的案例中,我的图像有时更高,有时更大。

这种风格就像一种魅力,确保所有图像都使用所有可用空间,保持比例而不是剪切:

.img {
   object-fit: contain;
   max-width: 100%;
   max-height: 100%;
   width: auto;
   height: auto;
}

这里有一个解决方案:

object-fit: cover;
width: 100%;
height: 250px;

您可以调整宽度和高度以满足您的需要,对象拟合属性将为您进行裁剪。

有关对象拟合属性和兼容性表的可能值的更多信息,请参见:https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit