粘性页脚
粘性页脚模式是指在内容短于视口高度的情况下,页面页脚“粘”在视口底部。在本食谱中,我们将介绍几种创建粘性页脚的技术。
依赖项
粘性页脚模式需要满足以下要求
- 当内容较短时,页脚粘在视口底部。
- 如果页面内容超出视口底部,页脚会被向下推,始终像往常一样位于内容下方。
本食谱
点击下面代码块中的“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 — 这可以防止它们在内容填充主要区域时收缩得更小。