Open Seasons123 opened 6 years ago
需求:将footer固定到底部。文章内容不足满屏时 footer在底部,超过满屏时footer在内容末尾。 这个方案亲自实践过,可以 :fallen_leaf: :
html部分
<div id="wrap">
<div id="main" class="clearfix">
<div id="content"></div>
<div id="side"></div>
</div>
</div>
<div id="footer"></div>
css部分
<style>
* {
padding: 0;
margin: 0;
font-size: 20px;
}
html, body, #wrap {
height: 100%;
}
body > #wrap {
height: auto;
min-height: 100%;
}
#main {
padding-bottom: 150px; /*必须使用和footer相同的高度 */
}
#footer {
position: relative;
margin-top: -150px; /*footer高度的负值 */
height: 150px;
clear: both;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
</style>
关键:就是加注释的那两行:
#main {
padding-bottom: 150px; /*必须使用和footer相同的高度 */
}
相当于是底部撑出一个高度来,这样底部就避免内容长的时候被它盖住 详细讲解可以看这篇 ,思路就是:
footer固定在底部。就是当内容区域比较少时,让footer也能正常定位到底部,以前我们使用js来达到这种效果,其实用css也是完全可以的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sticky footer</title>
<style type="text/css">
/* 第一步设置盒子为满屏大小 */
.box{
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
overflow: auto;
background: green;
}
/* 第二步子盒子设置最小高度且清除浮动 */
.box .main{
width: 100%;
min-height: 100%;
}
.box .main .content{
background: orange;
}
/* 第三步footer的高度和margin-top要相等 */
.box .footer{
position: relative;
width: 100%;
height: 100px;
background: #f3f3f3;
margin: -100px auto 0 auto;
clear: both;
text-align: center;
}
.clearfix{
display: inline-block;
}
.clearfix::after{
content: ".";
display: block;
height: 0;
line-height: 0;
visibility: hidden;
clear: both;
}
</style>
</head>
<body>
<div class="box">
<div class="main clearfix">
<div class="content">
<p>这里是内容区域</p>
<p>这里是内容区域</p>
<p>这里是内容区域</p>
</div>
</div>
<div class="footer">这是footer区域</div>
</div>
</body>
</html>
效果:
css让footer始终位于页面的最底部
html代码结构为:
第一种情况:footer随着进度条的滚动而滚动 这个在文章内容不足满屏时 footer不在底部,这种写法只满足随着滚动条的滚动而滚动 :-1:
第二种情况:footer固定在底部 :100: 我原来做的项目中是采用的这种方式
第三种实现方法:让footer固定在底部(转自阮一峰老师博客) :1234: 在实际的项目中一直没做尝试 可以使用flex布局,让footer固定在底部。有时,页面内容太少,无法占满一屏的高度,底栏就会抬高到 页面的中间。这时可以采用Flex布局,让底栏总是出现在页面的底部。注意的问题:设为Flex布局以后,子元素的float、clear和vertical-align属性将失效。
ps:解释一下vh: vh是相对于视窗的高度,视窗高度是100vh;视窗是指浏览器内部可视区的大小, window.innerWidth、window.innerHeight大小。