CSS 黏性底部 (Sticky Footer)
黏性底部是指當頁面內容不足以填滿視窗時,頁尾仍然固定在視窗底部;當內容超過視窗高度時,頁尾則跟隨內容顯示在最下方。
Flexbox 方式(推薦)
body {
min-height: 100vh;
display: flex;
flex-direction: column;
}
main {
flex: 1;
}
footer {
/* 不需要特別設定 */
}
<body>
<header>頁首</header>
<main>主內容</main>
<footer>頁尾</footer>
</body>
Grid 方式
body {
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
}
<body>
<header>頁首</header>
<main>主內容</main>
<footer>頁尾</footer>
</body>
使用 wrapper
如果不想直接在 body 上設定:
.wrapper {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.main-content {
flex: 1;
}
<div class="wrapper">
<header>頁首</header>
<main class="main-content">主內容</main>
<footer>頁尾</footer>
</div>
完整範例
基本頁面結構
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
display: flex;
flex-direction: column;
font-family: sans-serif;
}
header {
background: #333;
color: white;
padding: 16px 24px;
}
main {
flex: 1;
padding: 24px;
max-width: 1200px;
margin: 0 auto;
width: 100%;
}
footer {
background: #222;
color: white;
padding: 24px;
text-align: center;
}
帶有側邊欄的佈局
body {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.page-content {
flex: 1;
display: flex;
}
aside {
width: 250px;
background: #f5f5f5;
padding: 24px;
}
main {
flex: 1;
padding: 24px;
}
<body>
<header>頁首</header>
<div class="page-content">
<aside>側邊欄</aside>
<main>主內容</main>
</div>
<footer>頁尾</footer>
</body>
Grid 完整佈局
body {
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 250px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
header {
grid-area: header;
}
aside {
grid-area: sidebar;
}
main {
grid-area: main;
}
footer {
grid-area: footer;
}
/* 響應式 */
@media (max-width: 768px) {
body {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"footer";
}
aside {
display: none;
}
}
calc() 方式(舊方法)
較舊的方式,使用 calc() 計算:
.content {
min-height: calc(100vh - 60px - 100px); /* 扣除 header 和 footer 高度 */
}
header {
height: 60px;
}
footer {
height: 100px;
}
這種方式需要知道 header 和 footer 的精確高度,不如 Flexbox 或 Grid 靈活。
margin-top: auto 技巧
body {
min-height: 100vh;
display: flex;
flex-direction: column;
}
footer {
margin-top: auto;
}
這個方法也能達到相同效果,margin-top: auto 會將 footer 推到最底部。
注意事項
重置 margin
確保 body 沒有預設 margin:
body {
margin: 0;
min-height: 100vh;
display: flex;
flex-direction: column;
}
子元素 height: 100%
如果子元素需要 100% 高度,可能需要在 html 上也設定:
html, body {
height: 100%;
}
/* 或使用 min-height */
body {
min-height: 100vh;
}
避免與 position: fixed 衝突
如果有固定元素(如固定導航列),記得考慮其高度:
body {
min-height: 100vh;
display: flex;
flex-direction: column;
padding-top: 60px; /* 固定導航的高度 */
}