div元素在2个静态高度之间的100%高度

时间:2012-08-22 08:42:13

标签: html css height

我正在尝试使div具有100%的高度。这总是一个痛苦的屁股...... 我希望我的#wrapper是100%,而我的#middle也是如此......

<div id="wrapper" style="margin-left:auto; margin-right:auto; width:900px;">
    <div id="top" style="height: 100px;width:inherit;">
        This stays top, with static height.
    </div>
    <div id="middle" style="width:inherit;">
        This should take all space that is left in height...
    </div>
    <div id="footer" style="height:50px;width:inherit;">
        This stays in bottom, with static height
    </div>
</div>

JsFiddle demo

2 个答案:

答案 0 :(得分:2)

使用绝对定位和棘手的overflow: auto

,可以使用JS

html, body {
    height: 100%; 
}
#wrapper {
    position: relative;
    margin-left:auto; 
    margin-right:auto; 
    width:500px;
    height: 100%;
}
#top {
    height: 100px;
    width: 100%;
    background: blue;
}
#middle {
    position:absolute;
    bottom: 50px;
    top: 100px;
    overflow: auto;
    width: 100%;
    background: red;
}
#footer {
    position:absolute;
    bottom: 0px;
    height:50px;
    width: 100%;
    background: green;
}
<div id="wrapper">
    <div id="top">
        This stays top, with static height.
    </div>
    <div id="middle">
        This should take all space that is left in height...
    </div>
    <div id="footer">
        This stays in bottom, with static height
    </div>
</div>

注意:使用width: 100%;代替width: inherit;,IE7不支持

答案 1 :(得分:0)

嗯,如果我是正确的话,你可以尝试使用javascript或jquery。 别忘了链接jQuery。

<script type="text/javascript" language="javascript">
$(document).ready(function()
{   
    //minus 150 because > top = 100px, footer = 50px == 150px
    //offsetHeight gives you the height in pixels from the div "wrapper"
    newHeight = document.getElementById('wrapper').offsetHeight - 150;

    //updates the height of the div #middle
    $("#middle").css({'height' : newHeight});
});
</script>

它对我有用^^