Sticky Footer 是一种网页效果:如果内容不够长时,页脚固定在浏览器底部;如果内容足够长,页脚固定在页面的最底部。

1. 使用absolute

HTML

1
2
3
4
5
6
<body>
<div class="wrapper">
<div class="content">
<div class="footer">
</div>
</body>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
body {
height: 100%;
margin: 0;
}
.wrapper {
position: relative;
min-height: 100%;
}
.content {
padding-bottom: 50px;
}
.footer {
position: absolute;
bottom: 0;
height: 50px;
}

2. 使用margin-bottom 负值

HTML

1
2
3
4
5
6
7
<body>
<div class="wrapper">
content
<div class="push"></div>
</div>
<footer class="footer"></footer>
</body>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
html, body {
height: 100%;
margin: 0;
}
.wrapper {
min-height: 100%;

/* Equal to height of footer */
/* But also accounting for potential margin-bottom of last child */
margin-bottom: -50px;
}
.footer,
.push {
height: 50px;
}

3. 使用calc()

HTML

1
2
3
4
5
6
<body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body>

CSS

1
2
3
4
5
6
.content {
min-height: calc(100vh - 50px);
}
.footer {
height: 50px;
}


假如content中的最后一个元素有 margin-bottom 属性,这将导致 content 的高增加,这是需要调整calc(100vh - footerHeight - marginBottom)

4. 使用 flex 布局

HTML

1
2
3
4
5
6
<body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
html, body {
height: 100%;
}
body {
display: flex;
flex-direction: column;
}
.content {
flex: 1 0 auto;
}
.footer {
flex-shrink: 0;
}