使用具有未知高度div的CSS上下设置div为剩余高度

是否有可能使封装填充窗口的高度(不滚动)和中心div滚动,而不与周围的像素和JavaScript?

<div id="wrapper"> <h1>Header</h1> <div id="center"> <div style="height:1000px">high content</div> </div> <div id="footer">Footer</div> </div> 

基本上我希望标题在顶部可见,页脚始终在底部可见,并在中心有一个可滚动的内容,占据了翻新的高度。
页眉,页脚和中心divs的高度都是未知的(没有设置px或%,即可变的字体大小或填充)。 纯CSS可以吗?

2014年更新 :解决这个布局问题的现代方法是使用flexbox CSS模型 。 它受到所有主stream浏览器和IE11 +的支持。


2012年:单独使用CSS的正确方法是使用display: tabledisplay: table-row 。 所有主stream浏览器都支持这些,从IE8开始。 这不是使用表格来显示。 你会使用div:

 html, body { height: 100%; margin: 0; } .wrapper { display: table; height: 100%; width: 100%; background: yellow; /* just to make sure nothing bleeds */ } .header { display: table-row; background: gray; } .content { display: table-row; /* height is dynamic, and will expand... */ height: 100%; /* ...as content is added (won't scroll) */ background: turquoise; } .footer { display: table-row; background: lightgray; } 
 <div class="wrapper"> <div class="header"> <h1>Header</h1> <p>Header of variable height</p> </div> <div class="content"> <h2>Content that expands in height dynamically to adjust for new content</h2> Content height will initially be the remaining height in its container (<code>.wrapper</code>). <!-- p style="font-size: 4000%">Tall content</p --> </div> <div class="footer"> <h3>Sticky footer</h3> <p>Footer of variable height</p> </div> </div> 

来自Dan Dascalescu的跨浏览器解决scheme:

http://jsfiddle.net/Uc9E2

 html, body { margin: 0; padding: 0; height: 100%; } .l-fit-height { display: table; height: 100%; } .l-fit-height-row { display: table-row; height: 1px; } .l-fit-height-row-content { /* Firefox requires this */ display: table-cell; } .l-fit-height-row-expanded { height: 100%; display: table-row; } .l-fit-height-row-expanded > .l-fit-height-row-content { height: 100%; width: 100%; } @-moz-document url-prefix() { .l-scroll { /* Firefox requires this to do the absolute positioning correctly */ display: inline-block; } } .l-scroll { overflow-y: auto; position: relative; height: 1000px; } .l-scroll-content { position: absolute; top: 0; bottom: 0; height: 1000px; min-height:100px; } 
 <div class="l-fit-height"> <section class="l-fit-height-row"> <div class="l-fit-height-row-content"> <p>Header</p> </div> </section> <section class="l-fit-height-row-expanded"> <div class="l-fit-height-row-content l-scroll"> <div class="l-scroll-content"> <p>Foo</p> </div> </div> </section> <section class="l-fit-height-row"> <div class="l-fit-height-row-content"> <p>Footer</p> </div> </section> </div> 

使用overflow:auto会让你这样做。

演示

所以你在说什么是一个粘性的页脚。 我去了,做了更多的研究,这就是我对你的。

 <div id="wrapper" style="height:100%"> <div id="header" style="float:none;"><h1>Header</h1></div> <div style="overflow:scroll;float:none;height:auto;">high content</div> <div id="footer" style="clear:both;position:fixed;bottom:0px;"><h1>Footer</h1></div> </div> 

这会给你一个粘性的页脚。 关键是位置:固定和底部:0px; 不幸的是,这意味着它也hover在滚动视图中的任何内容之上。 到目前为止,似乎只有Javascript来解决这个问题,但我会继续寻找。