有時候頁面內容偏短,撐不開整個瀏覽器視窗高度,但我們仍希望 footer 能貼齊視窗底部,而不是緊跟著內容浮在半空中。以下用一個簡單的絕對定位方案來解決。
核心觀念是:讓 footer 的父層最小高度為 100%,再將 footer 設為相對父層的絕對定位並貼底(bottom: 0),同時在父層內容中預留 footer 的高度空間,避免內容被遮住。
<!-- 父層 -->
<div id="wapper">
<!-- 主要內容 -->
<div id="main-content">
</div>
<!-- 頁腳 -->
<div id="footer">
</div>
</div>
#wapper{
position: relative; /* 重要!讓 footer 相對於 wapper 定位 */
height: auto; /* 內容能撐開時也能正常顯示 */
min-height: 100%;
}
#footer{
position: absolute;
bottom: 0; /* 關鍵:貼底 */
left: 0; /* IE 下務必加上 */
height: 60px; /* footer 高度須為固定值 */
}
#main-content{
padding-bottom: 60px; /* 重要!為 footer 預留空間 */
}
上述寫法在現代瀏覽器都能正常運作,但 IE6 不支援 min-height,需另外處理。由於 IE 在高度不足時會自動撐開層級,只要針對它單獨指定 height: 100% 即可:
<!--[if IE 6]>
<style>
#wapper{height:100%;} /* IE 高度不夠時會自動撐開 */
</style>
<![endif]-->
透過這套「相對定位父層 + 絕對定位頁尾 + 預留空間」的組合,就能讓 footer 無論內容多寡都乖乖待在頁面最底部。