粘性頁尾
粘性頁尾模式是指在內容短於視口高度的情況下,頁面頁尾“粘”在視口底部。在本食譜中,我們將介紹幾種建立粘性頁尾的技術。
依賴項
粘性頁尾模式需要滿足以下要求
- 當內容較短時,頁尾粘在視口底部。
- 如果頁面內容超出視口底部,頁尾會被向下推,始終像往常一樣位於內容下方。
本食譜
點選下面程式碼塊中的“Play”按鈕,在 MDN Playground 中編輯示例。
html
<div class="wrapper">
<header class="page-header">This is the header</header>
<main class="page-body">
<p contenteditable>
The footer sticks to the bottom even though this paragraph is short. Add
content to this editable area to see the footer push down when needed to
fit the content.
</p>
</main>
<footer class="page-footer">Sticky footer</footer>
</div>
css
* {
box-sizing: inherit;
}
html {
height: 100%;
box-sizing: border-box;
}
body {
height: 100%;
font: 1.2em sans-serif;
}
.wrapper {
min-height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
}
.page-header,
.page-footer {
background-color: rgb(75 70 74);
color: white;
padding: 20px;
}
.page-body {
padding: 20px;
}
.page-body p {
border: 1px solid grey;
}
注意:在此示例和接下來的示例中,我們使用一個設定為 min-height: 100% 的包裝器。您也可以透過將 <body> 的 min-height 設定為 100vh,然後將其用作網格容器,來實現整頁的粘性頁尾。
已做出的選擇
在上面的示例中,我們使用 CSS 網格佈局實現了粘性頁尾。.wrapper 的最小高度為 100%,這意味著它與它所處的容器一樣高。然後,我們建立一個單列網格佈局,包含三行,每行用於佈局的一部分。
網格自動放置將按源順序放置我們的專案,因此標題進入第一個自動大小的軌道,主要內容進入 1fr 軌道,頁尾進入最後一個自動大小的軌道。1fr 軌道將佔用所有可用空間,因此會增長以填充間隙。
替代方法
您也可以使用 flexbox 建立粘性頁尾。
html
<div class="wrapper">
<header class="page-header">This is the header</header>
<main class="page-body">
<p contenteditable>
The footer sticks to the bottom even though this paragraph is short. Add
content to this editable area to see the footer push down when needed to
fit the content.
</p>
</main>
<footer class="page-footer">Sticky footer</footer>
</div>
css
* {
box-sizing: border-box;
}
html,
body {
box-sizing: border-box;
height: 100%;
padding: 0;
margin: 0;
font: 1.2em sans-serif;
}
.wrapper {
box-sizing: border-box;
min-height: 100%;
display: flex;
flex-direction: column;
}
.page-header,
.page-footer {
background-color: rgb(75 70 74);
color: white;
padding: 20px;
flex-grow: 0;
flex-shrink: 0;
}
.page-body {
padding: 20px;
flex-grow: 1;
}
.page-body p {
border: 1px solid grey;
}
flexbox 示例以相同的方式開始,但我們在 .wrapper 上使用 display:flex 而不是 display:grid;我們還將 flex-direction 設定為 column。然後我們將主要內容設定為 flex-grow: 1,將其他兩個元素設定為 flex-shrink: 0 — 這可以防止它們在內容填充主要區域時收縮得更小。