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

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

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

img {
  max-width: 500px;
}

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


当前回答

全屏演示:

img[data-attribute] {height: 100vh;}

请记住,如果观察端口高度大于图像,则图像将相对于差异自然降级。

其他回答

要保持响应图像,同时仍然强制图像具有一定的纵横比,可以执行以下操作:

HTML格式:

<div class="ratio2-1">
   <img src="../image.png" alt="image">
</div>

和SCSS:

.ratio2-1 {
  overflow: hidden;
  position: relative;

  &:before {
    content: '';
    display: block;
    padding-top: 50%; // ratio 2:1
  }

  img {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
  }
}

无论作者上传的图像大小如何,这都可以用于强制执行特定的纵横比。

感谢@Ksesohttp://codepen.io/Kseso/pen/bfdhg.查看此URL以了解更多比率和工作示例。

您可以将容器设置为显示:伸缩和对齐项目:居中(其他对齐项目值也适用)。您也可以在图像本身上设置对齐自身,而不是对齐项目。

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

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

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

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

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

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

您可以使用此选项:

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