看這個網頁的底部,為什麼始終乖乖待在頁面最下方?即使內容很少,它也 tetap 停在底部,而不會緊跟內容、在下方留下大片空白。這就是所謂的「粘性頁腳(sticky footer)」布局。下面是它的實現代碼:
<div id="wrap">
<div id="main" class="clearfix">
<div id="content">
</div>
<div id="side">
</div>
</div>
</div>
<div id="footer">
</div>
html, body, #wrap {height: 100%;}
body > #wrap {height: auto; min-height: 100%;}
#main {padding-bottom: 150px;} /* 必須使用和 footer 相同的高度 */
#footer {position: relative;
margin-top: -150px; /* footer 高度的負值 */
height: 150px;
clear:both;}
兼容性 Hack:
.clearfix:after {content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */
原理其實不複雜:讓整體容器撐滿視口高度,主內容區留出與頁腳等高的底部內邊距,再給頁腳一個等量的負上边距把它「拉」回視口底部,最後用 clearfix 清除浮動即可。