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

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

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

img {
  max-width: 500px;
}

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


当前回答

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')";

其他回答

您可以使用:-

transform: scaleX(1.2);

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

And

transform: scaleY(1.2);

更改高度而不更改宽度

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

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

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

这使用Javascript和HTML

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

使用伪元素进行垂直对齐怎么样?这更少的代码用于旋转木马,但我想它适用于每个固定大小的容器。它将保持纵横比,并在顶部/底部或左侧/写入最短尺寸时插入@灰色暗条。同时,图像通过文本对齐水平居中,通过伪元素垂直居中。

    > li {
      float: left;
      overflow: hidden;
      background-color: @gray-dark;
      text-align: center;

      > a img,
      > img {
        display: inline-block;
        max-height: 100%;
        max-width: 100%;
        width: auto;
        height: auto;
        margin: auto;
        text-align: center;
      }

      // Add pseudo element for vertical alignment of inline (img)
      &:before {
        content: "";
        height: 100%;
        display: inline-block;
        vertical-align: middle;
      }
    }

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')";