CSS 的簡單在於易學,困難在於尋找更好的方案。在 CSS 世界裡似乎沒有「完美」,只有「更適合」。本文介紹一種讓 footer 穩定貼在頁面底部的做法,是個人見過的方案中相對完善的一種。
我們希望 footer 無論內容多少,都能固定在頁面(或視窗)底部,而不是緊跟內容或隨滾動跑掉。
html, body, #sticker { height: 100%; }
body > #sticker { height: auto; min-height: 100%; }
#stickerCon { padding-bottom: 40px; }
#footer {
margin-top: -40px;
height: 40px;
width: 100%;
text-align: center;
line-height: 40px;
color: #ABA498;
font-size: 12px;
background: #fafafa;
border-top: 1px solid #E7E7E7;
}
<div id="sticker">
<div id="stickerCon"></div>
</div>
<div id="footer">footer</div>
關鍵在於幾個數值的呼應:#sticker 用 min-height: 100% 撐滿整個視窗高度;內容區 #stickerCon 預留 40px 的底部內距;而 footer 用 margin-top: -40px 向上提,正好填進這塊預留空間。這樣一來,內容少時 footer 貼在視窗底部,內容多時則被自然推到最下方,兩全其美。