响应式DIV,具有水平和垂直缩放的内在比率

时间:2013-05-31 11:02:05

标签: html css responsive-design aspect-ratio

我目前正在开发一个网站,其中包含大量具有特定比率的图像。我试图让div在水平和垂直方向上调整大小同时保持其宽高比,在以下两个网站上可以看到类似的效果:

http://www.bureaucollective.ch/

http://www.yesstudio.co.uk/

如您所见,图像在水平和垂直方向上调整大小,同时保持其宽高比。图像也在窗口中垂直居中,这是我要在我正在开发的网站中包含的内容。

目前我的代码如下:

body, html {
    height: 100%;
    background: #f0f0f0;
}

#content {
    background: #FFF;
    margin: 0 auto;
    min-height: 100%;
    width: 80%;
}

div.stretchy-wrapper {
    width: 80%;
    margin: 0 auto;
    padding-bottom: 56.25%; /* 16:9 */
    position: relative;
    background: #000;
}

div.stretchy-wrapper > div {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}

<body>
    <div id="content">
        <div class="stretchy-wrapper">
            <div></div>
        </div>
    </div>
</body>

2 个答案:

答案 0 :(得分:2)

这是一个与http://www.yesstudio.co.uk/非常相似的更新。

<强> HTML

<div id="content">
    <div class="stretchy-wrapper">
        <div></div>
    </div>
</div>

<强> CSS

<style>
body, html {
    height: 100%;
    background: #f0f0f0;
    overflow:hidden
}

#content {
    background: #FFF;
    margin: 0 auto;
}

div.stretchy-wrapper {
    margin: 0 auto;
    position: relative;
    background: #000;
    width:100%;
    height:100%
}

div.stretchy-wrapper > div {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}

</style>

<强> JS

    <script>
function resize(){
        var winwidth, winheight, conwidth, conheight, imgheight, imgwidth, top, left;
        winwidth = $(window).width();
        winheight = $(window).height();
        conwidth = winwidth - 260;
        if(conwidth < 493){ conwidth = 493; }
        conheight = winheight - 95;
        conratio = conwidth/conheight;
        imgwidth = 1200;
        imgheight = 800;
        imgratio = 1200/800;
        if(conratio < imgratio){
            width = conwidth;
            height = conwidth / imgratio;
        } else {
            height = conheight;
            width = conheight * imgratio;
        }
        if(width > imgwidth || height > imgheight){
            width = imgwidth;
            height = imgheight;
        }

        top = (winheight/2) - (height/2);
        left = (winwidth/2) - (width/2);

        arrowheight = Math.round((winheight - height) / 2);


        if(left < 130){left = 130; }
        $("#content").css("top",top+"px").css("left",left+"px");
        $("#content").css("height",height+"px").css("width",width+"px");
    }

$(window).resize(resize);

$(document).ready(function(e) {
resize();
});

</script>

最后这是一个有效的 Demo :)享受

答案 1 :(得分:0)

我会说使用Max-Width:100%但我一直在读这个...

http://unstoppablerobotninja.com/entry/fluid-images/

它是关于响应式图像 - 它会为您重新计算比例值。