更新
使用 display:flex 为现代浏览器 (2015) 执行此操作的简单方法:
html,
body {height:100%; padding:0; margin:0; width:100%;}
body {display:flex; flex-direction:column;}
#main {flex-grow:1;}
/* optional */
header {min-height:50px; background:green;}
#main {background:red;}
footer {min-height:50px; background:blue;}
<header>header</header>
<div id="main" role="main">content</div>
<footer>footer</footer>
上面允许固定高度的页眉和页脚(只需为样式添加高度)以及可变高度(如当前所示 - 可以根据页眉和页脚的内容而变化),其余部分由内容占据空间。
如果内容比文档长,页脚会被下推。
旧帖:
有几种方法可以用纯 css 做到这一点。基本上你需要从这样的 html 结构开始:
<div id="wrapper">
<div class="top"></div>
<div class="middle">
<div class="container">
</div>
</div>
<div class="bottom"></div>
</div>
版本 1 使用边框框,因此与旧版浏览器不兼容(您可能需要添加 moz、webkit 和 ms 前缀才能使其在所有浏览器上运行):
html,
body { height: 100%; margin: 0; padding: 0; }
#wrapper { padding: 100px 0 75px 0; height: 100%; box-sizing: border-box; }
.middle { min-height: 100%; position: relative; }
.top { margin-top: -100px; height: 100px; }
.bottom { margin-bottom: -75px; height: 75px; }
.container { padding: 10px; }
Version 1
Version 1 with content
Version 1 centred column
版本 2 使用绝对定位,并且对跨浏览器更友好:
html,
body {min-height:100%; padding:0; margin:0;}
#wrapper {padding:50px 0; position:absolute; top:0; bottom:0; left:0; right:0;}
.middle {min-height:100%;}
.top {margin-top:-50px; height:50px;}
.bottom {margin-bottom:-50px; height:50px;}
.container {padding:10px;}
Version 2
Version 2 with content
Version 2 centred column
版本 3 略微更改了 html,但如果您有可变高度的页眉和页脚,则更加健壮:
<div id="wrapper">
<div class="table">
<div class="top row"><div class="cell"></div></div>
<div class="middle row"><div class="container cell"></div></div>
<div class="bottom row"><div class="cell"></div></div>
</div>
</div>
CSS
html,
body {min-height:100%; padding:0; margin:0;}
#wrapper {position:absolute; top:0; bottom:0; left:0; right:0;}
.table {display:table; width:100%; height:100%;}
.row {display:table-row;}
.cell {display:table-cell;}
.middle {height:100%;}
.container {padding:10px;}
Version 3
Version 3 with different height header and footer
Version 3 with content
Version 3 centred column