CSS - 填充剩余高度(动态内容)

时间:2014-05-11 22:40:34

标签: css

<div id="header">
    <div>My</div>
    <div>Header</div>
</div>
<div id="content"></div>

在上面的标记中,如何让内容填满屏幕的其余部分(不滚动)? 如果标题高度固定,我知道如何使用绝对位置执行此操作,但我的标题高度是由其内容动态设置的(因此网站在移动设备上响应。)

顺便说一句:我正在寻找一个仅限CSS的解决方案,因为我认为JavaScript并不适合这类任务。

非常感谢,

1 个答案:

答案 0 :(得分:4)

最简单的方法是在身体中绘制背景并保持#content透明。的 DEMO 1 即可。

这样,您不介意#header#content高度。


如果您不介意IE7及更少,那么从HTML表格元素的defaut display:table/table-row/table-cell中取出display可能就是您所需要的, 在案例标题中未知高度 即可。的 DEMO 2

您的结构需要进行一些更新才能充当希望并避免从标题部分到内容部分的布局渲染中出现空白。

如果重置display以用作表属性,它将执行此操作并可以绘制列和行。

由于只有行属性才有用,因此Structure必须呈现为一个col和多行。

基本结构需要这样转变:

<div id="header" class="row">
    <div class="single">
        <div>My</div>
        <div>Header than can grow</div>
    </div>
</div>
<div id="content" class="row">
    <div class="single">
        <p>My Content that will fill remaining space untill page has to scroll</p>
    </div>
</div>

基本的CSS就是这样:

html, body {
    height:100%;
    width:100%;
    margin:0;
}
body {
    display:table;/* it will allow to grow over initial width specified */
    /* table-layout:fixed; only if you want to control width within value specified*/
    background:#edc;
}
.row {
    display:table-row;/* we want these elements to stack on top of each other, not to become cells aside each other */
}
.single {
    display:table-cell;/* this 'buffer' element is used to avoid layout to turn into multiple cols */
}
#content {
    height:100%;/* since layout is the one taken from table properties, it means  fill all space avalaible that #header doesn't use */
    background:#cde;
}

在这种情况下,* #header 有一个已知的*** height,可以设置为固定或绝对位置。 #content可以是100%height DEMO 3 ,更好:min-height:100%; DEMO 4

display:flex也可能有用,但仅适用于真正的年轻浏览器:)。


Example with display:flex;

html {
    height:100%;
}
body {
    margin:0;
    min-height:100%;
    background:#edc;
    display:flex;
    flex-direction:column;
}
#header {
/* nothing needed here */
}
#content {
    flex:1;/* since it is the only one getting a flex attitude, it will fill up all space avalaible*/
    background:yellow;
}