頁面內容較少時,頁腳飄在視窗中間;內容多時,頁腳正常隨內容下沉。需求:**內容少時頁腳貼底,內容多時頁腳自然流動**。
| 方案 | 原理 | 優點 | 缺點 | 推薦度 |
|---|---|---|---|---|
| Flexbox 佈局(現代首選) | body 為 flex column,main flex:1 撐開 | ★★★★★ | ||
| Grid 佈局 | body 為 grid,行模板 auto 1fr auto | ★★★★★ | ||
| 負 Margin + 側欄佔位(傳統經典) | wrapper min-height:100%,負 margin 抵消 footer 高度 | ★★★☆☆ | ||
| position: fixed | footer 固定視窗底部 | ❌ 不推薦 | ||
| calc() + min-height | main min-height: calc(100vh - header - footer) | ★★★★☆ |
<body class="site">
<header class="site-header">頁首</header>
<main class="site-main">主要內容</main>
<footer class="site-footer">頁腳</footer>
</body>
.site {
display: flex;
flex-direction: column;
min-height: 100vh; /* 關鍵:至少佔滿視窗高度 */
}
.site-main {
flex: 1; /* 關鍵:佔據剩餘空間,推送 footer 到底部 */
/* 等同 flex: 1 0 auto; */
}
.site-header,
.site-footer {
flex-shrink: 0; /* 防止被壓縮 */
}
優勢:footer 高度任意(不需固定)、無額外 DOM、無魔法數字、響應式天然適配。
.site {
display: grid;
grid-template-rows: auto 1fr auto; /* header / main / footer */
min-height: 100vh;
}
/* 子元素無需任何額外樣式 */
Grid 明確定義三行軌道,中間 `1fr` 自動分配剩餘空間,最直觀。
<body>
<div class="wrapper">
<header>頁首</header>
<main>內容</main>
<div class="footer-placeholder"></div> /* 關鍵佔位 */
</div>
<footer class="footer">頁腳</footer>
</body>
html, body { height: 100%; margin: 0; }
.wrapper {
min-height: 100%;
margin-bottom: -120px; /* footer 高度負值 */
padding-bottom: 120px; /* 保護內容不被 footer 遮蓋 */
}
.footer,
.footer-placeholder {
height: 120px; /* 必須固定高度 */
}
.footer-placeholder { clear: both; } /* 清除浮動 */
關鍵點:
.site-main {
min-height: calc(100vh - 80px - 120px); /* 100vh - header高 - footer高 */
/* 或用 CSS 變數 */
min-height: calc(100vh - var(--header-h) - var(--footer-h));
}
移動端陷阱:`100vh` 包含瀏覽器地址欄,滾動時地址欄隱藏會導致視窗高度變化、內容跳動。解決:
.site-main {
display: flex;
flex-direction: column;
flex: 1;
overflow: auto; /* 內部滾動 */
}
.sticky-sidebar {
position: sticky;
top: 1rem;
align-self: flex-start; /* 防止被拉伸 */
max-height: calc(100vh - 2rem);
overflow: auto;
}
| 現象 | 原因 | 排查 |
|---|---|---|
| Footer 仍在中間 | body 無 min-height:100vh 或 flex-direction 錯誤 | 檢查 html/body 高度鏈、flex 方向 |
| 內容被 Footer 遮蓋 | 缺少 padding-bottom / placeholder | 補齊保護空間 |
| Footer 高度變化導致跳動 | 負 margin 方案需固定高度 | 改用 Flex/Grid 或 JS 同步高度 |
| 移動端地址欄導致 100vh 不準 | vh 包含地址欄 | 用 dvh、Flex/Grid、或 JS 方案 |
Sticky Footer 是 CSS 佈局的「Hello World」級經典問題。現代 CSS 以 Flex/Grid 徹底解決了「需要知道高度」這一核心痛點,請毫不猶豫地使用它們。