在项目中前端er会遇到这种需求,页脚固定,这个固定指的是当内容较少时,页脚固定在浏览器底部(这种情况我们会考虑position:fixed),当内容足够多,浏览器视口高度小于内容高度时,页脚固定资页面内容页面的底部(这时会发现position:fixed满足不了需求)。
content内容较少
//html
<header> I am header</header>
<div class="content">内容高度低</div>
<footer></footer>
//css
footer {
position: fixed;
width: 100%;
height: 60px;
background: red;
bottom: 0;
left: 0;
}
content内容足够多,用fixed布局会发现页脚footer会覆盖在内容上
//html
<header> I am header</header>
<div class="content">
<p>test</p>
...<!--a lot of p here-->
<p>test</p>
</div>
<footer></footer>
//css
footer {
position: fixed;
width: 100%;
height: 60px;
background: red;
bottom: 0;
left: 0;
}
很明显这不是我们想要的,解决上面的问题,我们需要用到”sticky footer”。
sticky footer应用场景是:当内容足够少时,页脚会固定在浏览器底部,当内容足够多时,页脚会固定在页面底部,这里的足够少和足够多也就是内容区的高度相对浏览器或者视口的高度比较而言。
实现sticky footer的方式有很多种,本文介绍一种常用的方法,或者说是通用方法。
内容较少
//html
<body>
<div class="container">
<header> I am header</header>
<div class="content">
<p>test</p>
<p>test</p>
<p>test</p>
</div>
</div>
<footer>footer</footer>
</body>
//css
html,body {
height: 100%;
margin: 0;
padding:0;
}
header {
background: green;
}
.container {
min-height: 100%;
height: auto;
overflow: auto;
}
.content {
padding-bottom: 60px;
}
footer {
position: relative;
width: 100%;
height: 60px;
margin-top: -60px;
background: red;
clear: both;
}
这里的关键是设置
1)html,body的height为100%,margin padding为0,如果html,body的高度没有设置为100%,那么就无法实现这样的效果(可以自己尝试)。
2)header和content用一个容器container div包裹,设置容器的min-height为100%,height:auto。
3)设置content的padding-bottom,主要一定不能写成margin-bottom
这里值得注意的是如果container容器只有content div需要设置overflow:auto,否则即使内容很少,也会出现滚动条,所以无论container是否只有content内容,一般都设置overflow:auto,这样可以避免出现滚动条。
content里面有很多内容,比如有很多p段落。这时footer没有固定在视口的底部,而是固定在页面的底部。