两种最常用的Sticky footer布局方式

Sticky footer布局是什么?

我们所见到的大部分网站页面,都会把一个页面分为头部区块、内容区块和页脚区块,当头部区块和内容区块内容较少时,页脚能固定在屏幕的底部,而非随着文档流排布。当页面内容较多时,页脚能随着文档流自动撑开,显示在页面的最底部,这就是Sticky footer布局。

图示说明

  • 当内容较少时,正常的文档流效果如下图

正常文档流.jpg

在正常的文档流中,页面内容较少时,页脚部分不是固定在视窗底部的,这时就要用到Stickyfooter布局。

  • Sticky footer布局效果如下图

Sticky footer布局.jpg

这样就符合我们的预期效果,可以看出Sticky footer布局的应用场景还是非常广泛的。

实现方式

负margin布局方式

html代码:

<div class="wrapper clearfix">
    <div class="content">
      // 这里是页面内容
    </div>  
</div>
<div class="footer">
    // 这里是footer的内容
</div>

css代码:

.wrapper {
    min-height: 100%;
}

.wrapper .content{
    padding-bottom: 50px; /* footer区块的高度 */
}

.footer {
    position: relative;
    margin-top: -50px;  /* 使footer区块正好处于content的padding-bottom位置 */
    height: 50px;
    clear: both;
}

.clearfix::after {
    display: block;
    content: ".";
    height: 0;
    clear: both;
    visibility: hidden;
}

注意:content元素的padding-bottomfooter元素的高度以及footer元素的margin-top值必须要保持一致。

这种负margin的布局方式,是兼容性最佳的布局方案,各大浏览器均可完美兼容,适合各种场景,但使用这种方式的前提是必须要知道footer元素的高度,且结构相对较复杂。

flex布局方式

html代码:

<div class="wrapper">
    <div class="content">这里是主要内容</div>
    <div class="footer">这是页脚区块</div>  
</div>

css代码:

.wrapper {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}
.content {
    flex: 1;
}
.footer {
    flex: 0;
}

这种布局方式结构简单,代码量少,也是较为推荐的布局方式。

小结

Sticky footer布局是十分常见的一种页面布局形式,实现的方法也比较多,以上两种方法最为常用,且基本可以满足所有应用场景。

posted @ 2017-06-02 23:59  陌路黄昏后  阅读(3874)  评论(1编辑  收藏  举报