Sticky footers解决方案总结

来源:互联网 发布:程序员保密费 编辑:程序博客网 时间:2024/05/22 03:45

在实际开发中,我们经常会遇到这样一个需求:如果页面小于一屏时,页脚块需要固定在页面底部,如果页面超过一屏时,页脚块向下推送。

这种需求很常见,也很实用,下面总结了4种方法来实现这种需求:

父级relative解决方案

当父级不要求使用fixed且footer块高度已知时比较适用,主要设置container块相对定位position:relative;footer块为绝对定位position:absolute

html结构:

    <div class="container">      <div class="main">        <p>正文内容</p>      </div>      <div class="footer">        底部内容      </div>    </div>

css样式:

html,body{    margin:0;    height: 100%;}.container{    position: relative;    min-height: 100%;    padding-bottom:60px;    box-sizing: border-box; } .footer{    height: 60px;    position: absolute;    left:0;    bottom:0;    width: 100%;    background: #000;    color:#fff; }

当内容小于一屏时,效果如下:

这里写图片描述

内容大于一屏时,效果如下:

这里写图片描述

可以看到,不论内容小于一屏还是大于一屏,footer始终固定在底部。

父级fixed解决方案

制作弹出层时,就需要将父级设为fixed,此时就需要用到如下方式了

fixed方式的html结构层级要比relative方式复杂,需要添加main-wrapper层解决当内容小于一屏时,footer依然固定在页面底部的需求。
此方式要注意设置.main{padding-bottom: 60px;}和 .footer{margin-top: -60px;}

html:

<div class="container">    <div class="main-wrapper">        <div class="main">            <p>正文部分</p>            <p>正文部分</p>            <p>正文部分</p>        </div>    </div>    <div class="footer">        x    </div></div>

css:

.container{    position: fixed;    z-index:2;    left:0;    top:0;    width: 100%;    height: 100%;    overflow: auto;    background: rgba(0,0,0,0.6);    backdrop-filter: blur(10px);    color: #fff; } .main-wrapper{    width: 100%;    min-height:100%; } .main{    padding-bottom: 60px; } .footer{    margin-top: -60px;    height: 60px;    font-size: 30px;    text-align: center; }

效果如下图:

这里写图片描述

Flexbox解决方案

Flexbox方式非常简洁,不仅html结构简单,而且footer块高度未知也适用。

重点是将父级container的display设为flex,默认情况下子元素布局为row(即横向布局),所以设置flex-direction: column;可将子元素(main和footer)设为纵向布局,然后将main块设为flex:1;因为当flex>0时,元素就会灵活的控制自己的尺寸,来适配容器的剩余空间

html:

<div class="container">  <div class="main">      <p>正文部分</p>      <p>正文部分</p>      <p>正文部分</p>   </div>   <div class="footer">      x   </div></div>

css:

.container{    position: fixed;    z-index:2;    width: 100%;    height: 100%;    left:0;    top:0;    overflow: auto;    display: flex;    display: -webkit-flex;    flex-direction: column;    -webkit-flex-direction: column;    background: rgba(0,0,0,0.6);    color:#fff; } .main{    flex: 1; } .footer{    text-align: center;    font-size: 30px; }

效果如下图:

这里写图片描述

calc函数

重点是利用calc()函数来设置main块的最小高度。其中100vh为屏幕可视高度,需要注意的是,运算符前后都需要保留一个空格。
calc()用法详解

html:

<div class="container">  <div class="main">      <p>正文部分</p>      <p>正文部分</p>      <p>正文部分</p>   </div>   <div class="footer">      x   </div></div>

css:

.container{    position: fixed;    width: 100%;    height: 100%;    left:0;    top:0;    background: rgba(0,0,0,0.5);    color: #fff; } .main{    min-height: calc(100vh - 60px);      //运算符-前后需要添加空格 } .footer{    text-align: center;    font-size: 30px;    height: 60px;    line-height: 60px; }
0 0
原创粉丝点击