萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS + JS 實現頁腳自適應固定底部:內容少時吸底、內容多時隨內容

需求分析

  • 內容不滿一屏 → 頁腳固定在視口底部
  • 內容超過一屏 → 頁腳跟隨內容自然流動至文檔末尾
  • 視口縮放時實時響應

方案一:JavaScript 動態計算(原文方案)

<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>

方案二:CSS Flexbox 純樣式方案(現代首選,無 JS)

<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; }  /* 不被壓縮 */

方案三:CSS Grid 純樣式方案

.page-wrapper {
  display: grid;
  grid-template-rows: 1fr auto;  /* 內容自適應、頁腳固定高度 */
  min-height: 100vh;
}

方案四:經典負 Margin 方案(IE8+ 兼容)

.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 方案。理解各方案原理與取捨,是前端佈局基本功的重要體現。

copyright © 萬盛學電腦網 all rights reserved