在实际开发中,咱们常常会遇到这样一个需求:若是页面小于一屏时,页脚块须要固定在页面底部,若是页面超过一屏时,页脚块向下推送。
这种需求很常见,也很实用,下面总结了4种方法来实现这种需求:css
当父级不要求使用fixed且footer块高度已知时比较适用,主要设置container块相对定位position:relative;footer块为绝对定位position:absolutehtml
html结构:web
<div class="container"> <div class="main"> <p>正文内容</p> </div> <div class="footer"> 底部内容 </div> </div>
css样式:app
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始终固定在底部。flex
制做弹出层时,就须要将父级设为fixed,此时就须要用到以下方式了spa
fixed方式的html结构层级要比relative方式复杂,须要添加main-wrapper层解决当内容小于一屏时,footer依然固定在页面底部的需求。
此方式要注意设置.main{padding-bottom: 60px;}和 .footer{margin-top: -60px;}code
html:htm
<div class="container"> <div class="main-wrapper"> <div class="main"> <p>正文部分</p> <p>正文部分</p> <p>正文部分</p> </div> </div> <div class="footer"> x </div> </div>
.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方式很是简洁,不只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()函数来设置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; }