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

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

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

其他回答

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

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

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以了解更多比率和工作示例。

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

您可以使用此选项:

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