0

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

简单地设置...

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

没有给我图像的比例尺寸。

我怎样才能做到这一点?

4

2 回答 2

1

我发现唯一一致的解决方案是 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);
}
于 2015-11-04T20:38:15.413 回答
0

图像处理在 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/

于 2015-11-04T21:06:11.367 回答