CSS使元素固定底部的方法

固定在底部包括两种情况,第一种是当页面内容尚未填充满的时候,页脚需要固定在底部,第二种是页面填充满后,页脚需要随页面内容的增加而填充在主体内容的下方。

最简单粗暴的方法就是给元素设置position:fixed;bottom:0;不过这样写在移动端或者设备高度不高的情况下,会严重影响用户体验。前段时间看饿了么视频的时候,视频里面黄奕老师讲到一个黑科技’Sticky footers’,然后百度了一下,实现了他里面的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<style type="text/css">
html,body{height:100%}
.footer {margin-top:-30px;height:30px;background-color:#eee;}
.wrap{min-height:100%}
.main{padding-bottom:30px;overflow:hidden;}
</style>
</head>
<body>
<div class="wrap">
<div class="main">这里是网页的主体</div>
</div>
<div class="footer">这里是页脚</div>
</body>
</html>

demo看这里

还可以使用flex布局来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
#content {
flex: 1;
}

#footer {
line-height: 30px;
text-align: center;
}
</style>
</head>
<body>
<div id="content">
</div>
<div id="footer">&copy; Brook.inc</div>
</body>
</html>

这里看demo


CSS使元素固定底部的方法
https://xypecho.github.io/2018/01/24/CSS使元素固定底部的方法/
作者
很青的青蛙
发布于
2018年1月24日
许可协议