<div id="info">頁面主內容...</div>
<div id="bottom">頁腳內容</div>
<script>
function fixFooter() {
const infoH = document.getElementById('info').scrollHeight;
const bottomH = document.getElementById('bottom').scrollHeight;
const viewH = document.documentElement.clientHeight;
const bottom = document.getElementById('bottom');
if (infoH + bottomH < viewH) {
bottom.style.position = 'absolute';
bottom.style.bottom = '0';
bottom.style.width = '100%';
} else {
bottom.style.position = 'static';
bottom.style.bottom = 'auto';
bottom.style.width = 'auto';
}
}
// 初始化 + 視口變化監聽
fixFooter();
window.addEventListener('resize', fixFooter);
// 現代寫法:防抖優化
// window.addEventListener('resize', debounce(fixFooter, 100));
</script>
<body>
<div class="page-wrapper">
<main class="content">主內容...</main>
<footer class="footer">頁腳</footer>
</div>
</body>
html, body { height: 100%; margin: 0; }
.page-wrapper {
display: flex;
flex-direction: column;
min-height: 100vh; /* 關鍵:至少滿視口高 */
}
.content { flex: 1; } /* 關鍵:佔據剩餘空間,推開 footer */
.footer { flex-shrink: 0; } /* 不被壓縮 */
.page-wrapper {
display: grid;
grid-template-rows: 1fr auto; /* 內容自適應、頁腳固定高度 */
min-height: 100vh;
}
.wrapper { min-height: 100%; margin-bottom: -80px; } /* 頁腳高度 80px */
.footer { height: 80px; }
.push { height: 80px; } /* 佔位元素,防止內容被頁腳遮擋 */
/* HTML: .wrapper > .content + .push + .footer */
| 方案 | JS 依賴 | 瀏覽器支援 | 代碼複雜度 | 效能 | 推薦指數 |
|---|---|---|---|---|---|
| JS 計算 | 是 | 全瀏覽器 | 中 | 需監聽 resize,重排風險 | ⭐⭐ (維舊專案) |
| Flexbox | 否 | IE10+ | 極低 | 極佳,無重排 | ⭐⭐⭐⭐⭐ (現代首選) |
| Grid | 否 | 現代瀏覽器 | 極低 | 極佳 | ⭐⭐⭐⭐ (新專案) |
| 負 Margin | 否 | IE8+ | 中 | 良好 | ⭐⭐⭐ (需兼容 IE9-) |
<!DOCTYPE html>
<html>
<head>
<style>
html, body { height: 100%; margin: 0; }
.site { display: flex; flex-direction: column; min-height: 100vh; }
.site-main { flex: 1; }
.site-footer { flex-shrink: 0; }
</style>
</head>
<body>
<div class="site">
<header class="site-header">Header</header>
<main class="site-main">Content</main>
<footer class="site-footer">Footer</footer>
</div>
</body>
</html>
頁腳自適應固定底部是經典佈局需求。現代專案請直接使用 Flexbox/Grid 純 CSS 方案:零 JS、零重排、語義清晰、響應式天然支援。僅在必須支援 IE9 以下環境時,才考慮負 Margin 或 JS 方案。理解各方案原理與取捨,是前端佈局基本功的重要體現。