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

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

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

img {
  max-width: 500px;
}

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


当前回答

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

其他回答

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

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

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

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

全屏演示:

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

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

这里有一个解决方案:

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

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

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

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

setec的解决方案适用于自动模式下的“收缩到适合”。但是,为了最佳地扩展以适应“自动”模式,您需要首先将接收到的图像放入临时id,检查它是否可以在高度或宽度上扩展(取决于其纵横比v/s,即显示块的纵横比),

$(".temp_image").attr("src","str.jpg" ).load(function() { 
    // callback to get actual size of received image 

    // define to expand image in Height 
    if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
        $(".image").css('height', max_height_of_box);
        $(".image").css('width',' auto');
    } else { 
        // define to expand image in Width
        $(".image").css('width' ,max_width_of_box);
        $(".image").css('height','auto');
    }
    //Finally put the image to Completely Fill the display area while maintaining aspect ratio.
    $(".image").attr("src","str.jpg");
});

当接收到的图像小于显示框时,这种方法很有用。您必须将它们保存在服务器上的原始小尺寸,而不是其扩展版本,以填充更大的显示框,以节省大小和带宽。

这是精神上的。使用比例缩小属性-它可以自行解释。

内联样式:

<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />

这将阻止flex拉伸它。在这种情况下,图像将达到其父容器宽度的50%,并且高度将缩小以匹配。

保持简单。