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

<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;
}

其他回答

backgroundsize属性仅为ie>=9,但如果这对您来说很好,您可以使用带有背景图像的div并设置backgroundsize:contain:

div.image{
    background-image: url("your/url/here");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

现在,您只需将div大小设置为所需的大小,图像不仅保持其纵横比,还将在div中垂直和水平集中。不要忘记在css上设置大小,因为div本身没有width/height属性。

这种方法与setecs答案不同,使用这种方法,图像区域将是恒定的,并由您定义(根据div大小和图像纵横比,水平或垂直地留出空格),而setecs回答将为您提供一个与缩放图像大小完全相同的框(没有空格)。

编辑:根据MDN背景大小文档,您可以使用专有过滤器声明模拟IE8中的背景大小属性:

虽然Internet Explorer 8不支持背景大小属性,但可以使用非标准的-ms过滤器函数模拟其某些功能:

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";

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

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

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

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

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

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

可以使用纵横比属性css

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

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