紧贴底部的页脚

2,132 阅读3分钟
原文链接: segmentfault.com

前言

在写前端页面时,经常会遇到这种情况:有一个具有块级样式的页脚,当页面内容足够长时它一切正常;有的时候,由于页面长度不够,页面底部的页脚会很尴尬的跑上来;页脚不能像我们期望中那样“紧贴”在视口的最底部,而是紧跟在内容的下方。

那么怎样做到内容多时页脚在内容下方,内容少时页脚“紧贴”在视口底部?我总结了四种方法。

正文

首先我先写一个简单的页面结构,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>紧贴底部的页脚</title>
</head>
<body>
    <div class="wrapper">
        <header>
            <span>Header</span>
        </header>
        <main>
            <p>我是内容</p>
        </main>
    </div>
    <footer>
        <span>Fotter</span>
    </footer>
</body>
</html>

再页面加点公共样式:

*{
    padding:0;
    margin: 0;
}
header{
    line-height: 80px;
}
header,footer{
    background-color: #ccc;
    text-align: center;
}
main{
    text-align: center;
    font-size: 30px;
}

接下来我们用四种不同的方法来实现如何让页脚紧贴底部。

方法一

/* footer的每一级父元素都为100%高 */
html,body {
    height: 100%;
    width: 100%;
}
/* 这里将页面内容最小高度设为100%;撑满屏幕,
然后使用margin-bottom负值把页脚吸上来,
最后设置底部内边距用来填充内容过多时被遮挡的页脚。 */
.wrapper{
    height: auto !important;
    min-height: 100%;
    height: 100%;
    margin-bottom: -80px;
    padding-bottom: 80px;
    box-sizing: border-box;
}
footer{
    height: 80px;
}
        

方法二

方法二和方法一比较类似,只是用伪元素取代了内边距。代码如下:

html,body {
    height: 100%;
    width: 100%;
}
.wrapper{
    height: auto !important;
    min-height: 100%;
    height: 100%;
    margin-bottom: -80px;
}
/* 这里用伪元素取代了方法一中.wrapper的内边距 */
.wrapper::after{
    content: "";
    display: block;
    height: 80px;
}
footer{
    height: 80px;
}

方法三

方法三借助视口相关的长度单位以及calc()函数。这两个东西都只能兼容到IE9。

.wrapper{
    min-height:calc(100vh - 80px);
}
footer{
    height: 80px;
}

前三种方法都有一定的局限性,都要给页脚设置固定的高度,不够灵活。有没有更加灵活的方法呢?当然有,那就是我们方法四了。

方法四

方法四用到了CSS3中的布局神器Flexbox

body {
    display: flex;
    flex-flow: column;
    min-height: 100vh;
}
.wrapper {
    flex: 1; 
}

这样就可以了!我们只需要四行简单的代码,就完美实现了紧贴底部的页脚。Flexbox是不是相当霸气?
Flexbox兼容性不是很好(万恶的IE),但在移动端还是不错的。可以放心使用。

后记

上面是我总结的四种方法,如果还有什么更好的方法,欢迎共同探讨!

参考资料:
CSS 总在底部的页脚
CSS揭秘