如何设置一个相对于自身高度而非宽度的响应比例图像

How do I set a responsive proportional image that is relative to its own height – NOT its width

本文关键字:响应 例图 高度 图像 设置 何设置 相对于 一个      更新时间:2023-09-26

如何设置相对于自身高度而非宽度的响应比例图像?

简单地设置。。。

img{
    width: auto;
    height: 100%;
}

并没有为我的图像提供成比例的尺寸。

我该怎么做?

我发现唯一一致的解决方案是javascript解决方案。

介绍naturalWidth和naturalHeight。。除IE8外,所有浏览器都支持。IE8还有一个变通方案。(http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/)

如果你不介意使用jquery和下划线,你可以这样设置每个宽度

$(window).load( function() {
    function imgWidth(){
        $("img").each( function(){
            nWidth = $(this)[0].naturalWidth;
            nHeight = $(this)[0].naturalHeight;
            nRatio = nWidth/nHeight;
            curHeight = $(this).height();
            $(this).css("width", curHeight*nRatio);
        });
    }
    imgWidth();
    var updateLayout = _.debounce( function(e) {
        imgWidth();
    }, 500);
    window.addEventListener("resize", updateLayout, false);
}

HTML/CSS中的图像处理变得非常复杂。在许多场景中,直接在img上的高度标记会被忽略,这取决于div属性。我认为最简单的方法是创建一个以所讨论的图像集为背景的div。

.img-div {
height:x; width:x;
background:url(file/path/here.svg);
background-position:center;
background-size:auto 100%;

下面是一个演示:https://jsfiddle.net/JTBennett/nukLf5m3/