如何在页眉和页脚之间制作100%的div高度?

时间:2014-07-20 13:28:48

标签: css css3

问题在这里:http://jsfiddle.net/x8XZ6/3/

HTML

<div id="top"></div>
<div id="content">Why this div is not 100% height? I need this to fill all the way to the start of the footer if content is to little. If content extends beyond the blue footer, it should push the footer down.</div>
<div id="anchored-footer"></div>

CSS

* { margin: 0; padding: 0 }
html { height: 100%; }
body {
    position: relative; min-height: 100%;
    height: 0;
    /* height: 0; interestingly, if height is set to 0, it expands 100% (see also #content margin-bottom) */
    /* but I need it to extend up to the blue bar only. */
}
#top {
    height: 50px;
    background-color: red;
}
#anchored-footer {
    position: absolute;
    bottom: 0;
    height: 50px;
    background-color: blue;
    width: 100%;
}
#content {
    border: 5px solid green; /* because I need this border to go all around the content area */
    background-color: yellow;
    height: 100%;
    /* margin-bottom: -50px; can a negative margin work here? */
}

这可以在不使用绝对定位标题的情况下实现吗?

3 个答案:

答案 0 :(得分:3)

你需要将BODY改为高度:100%;

working demo

CSS

* { margin: 0; padding: 0 }
html { height: 100%; }
body {
    position: relative; height: 100%;
}
#top {
    height: 50px;
    background-color: red;
}
#anchored-footer {
    bottom: 0;
    height: 50px;
    background-color: blue;
    width: 100%;
}
#content {
    border: 5px solid green; /* because I need this border to go all around the content area */
    background-color: yellow;
    min-height:calc(100% - 110px);
}

*注意:没有位置:绝对使用...你根本不需要它,特别是如果你想要你的内容压低你的页脚..那么绝对不要使用绝对。

答案 1 :(得分:1)

我建议你做以下事情:

body {
    position: relative;
    min-height: 100%; /* to fill screen 100% even with less content */
    height: 100%; /* to allocate only 100% height */
}

#top {
    height: 50px;
    background-color: red;
    top: 0;
}
#anchored-footer { /* No absolute positioning */
    height: 50px;
    background-color: blue;
    width: 100%;
}
#content {
    border: 5px solid green;
    background-color: yellow;
    min-height: calc(100% - 110px); /* allocate the remaining height except the header + footer + borders and assign as minimum height */
    height: auto; /* allow content to expand when height exceeds the min height */
}

Demo | Demo with lot of content

答案 2 :(得分:0)

如果您不担心IE8浏览器,那么您可以使用calc属性来实现此目的。

 html, body{width:100%;}
 #content {
 border: 5px solid green;
 background-color: yellow;
 height:calc(100% - 110px); /* 50px header + 50px footer + 10px border */
 }

DEMO