在实际开发中,我们经常会遇到这样一个需求:如果页面小于一屏时,页脚块需要固定在页面底部,如果页面超过一屏时,页脚块向下推送。
下面为在开发中兼容性最好,最为常用的两种解决方案:
1.父级relative
当父级不要求使用fixed且footer块高度已知时比较适用,主要设置container块相对定位position:relative;footer块为绝对定位
position:absolute
html结构:
<div class="container clearfix">
<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;
}
2.父级fixed解决方案
制作弹出层时,就需要将父级设为fixed,此时就需要用到如下方式了
fixed方式的html结构层级要比relative方式复杂,需要添加main-wrapper层解决当内容小于一屏时,footer依然固定在页面底部的需求。
此方式要注意设置.main{padding-bottom: 60px;}和 .footer{margin-top: -60px;}
html结构:
<div class="container">
<div class="main-wrapper clearfix">
<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区块的高度 */
}
.footer{
position: relative;
margin-top: -60px;/* 使footer区块正好处于content的padding-bottom位置 */
height: 60px;
font-size: 30px;
text-align: center;
clear: both;
}
.clearfix::after {
display: block;
content: ".";
height: 0;
clear: both;
visibility: hidden;
}