萬盛學電腦網

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

CSS Sticky Footer 經典方案:負 Margin + Padding 搭配,讓頁腳永遠停在視口底部

當頁面內容不足一屏時,頁腳懸浮在內容下方而非視口底部,視覺割裂感強。經典 Sticky Footer(粘性頁腳) 方案利用負 Margin 抵消 Padding,配合 min-height: 100%,實現:內容少時頁腳吸底,內容多時頁腳自然隨內容下沉。兼容 IE6+、所有現代瀏覽器。

核心 HTML 結構

<body>
  <div id="wrapper">
    <header id="header">Header</header>
    <main id="content">
      <aside id="sidebar">Sidebar</aside>
      <article id="main-content">Main Content</article>
    </main>
    <div class="push"></div> /* 關鍵:佔位頁腳高度 */
  </div>
  <footer id="footer">Footer</footer>
</body>

核心 CSS

* { margin: 0; padding: 0; } /* 重置 */

html, body { height: 100%; } /* 建立 100% 高度參考鏈 */

#wrapper {
  min-height: 100%;          /* 現代瀏覽器 */
  margin: 0 auto -150px;     /* 負 margin-bottom = 頁腳高度 */
  width: 770px;              /* 定寬居中示例 */
}
* html #wrapper { height: 100%; } /* IE6 min-height hack */

.push { height: 150px; }     /* 必須 = 頁腳高度,撐開 wrapper 底部 */

#footer {
  height: 150px;             /* 頁腳固定高度 */
  width: 770px;
  margin: 0 auto;
  background: #333; color: #fff;
}

/* 內容區佈局示例 */
#content { overflow: hidden; } /* 清除浮動 */
#sidebar { float: left; width: 200px; }
#main-content { float: right; width: 570px; }

原理圖解

  1. html/body height:100% → 視口高度基準
  2. #wrapper min-height:100% → 至少滿屏高度
  3. .push 佔位 150px → 撐開 #wrapper 底部預留頁腳空間
  4. #wrapper margin-bottom: -150px → 向上「吸回」頁腳高度,使 #footer 能移入視口底部
  5. 內容少時:#wrapper 高度 = 視口高,.push 撐開空間,#footer 吸附底部
  6. 內容多時:#wrapper 高度 > 視口高,#footer 自然隨內容流動至文檔末尾

現代 Flexbox 方案(更簡潔、無固定高度限制)

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh; /* 視口高度單位,無需 html height:100% */
}
#wrapper { flex: 1; } /* 佔據剩餘空間,自動推開 footer */
#footer { /* 無需固定高度 */ }
  • 優勢:頁腳高度自適應、無額外 DOM、無負 margin hack、IE10+ 完美支援
  • IE9- 需降級或 Polyfill

Grid 方案(最語義化)

body {
  display: grid;
  grid-template-rows: auto 1fr auto; /* header / main / footer */
  min-height: 100vh;
}
header { grid-row: 1; }
#wrapper { grid-row: 2; }
footer { grid-row: 3; }

避坑清單

  • ❌ #wrapper 設置 height: 100% 而非 min-height → 內容超屏時頁腳固定在視口底部遮擋內容
  • ❌ .push 高度 ≠ #footer 高度 → 吸底位置偏移
  • ❌ #footer 未設定固定高度(傳統方案要求) → 無法精確計算負 margin
  • ❌ 忘記 overflow: hidden 或 flow-root 清除 #content 內部浮動 → #wrapper 高度計算錯誤

Sticky Footer 是 CSS 佈局經典考題,理解「負 Margin 回拉 + 佔位元素撐開」的幾何邏輯,能舉一反三解決各類「底部吸附」需求。現代項目首選 Flex/Grid 一行代碼解決,舊專案維護時經典方案依然可靠好用。

copyright © 萬盛學電腦網 all rights reserved