在實際開發中,我們經常會遇到這樣一個需求:如果頁面小於一屏時,頁腳塊需要固定在頁面底部,如果頁面超過一屏時,頁腳塊向下推送。
下面爲在開發中兼容性最好,最爲常用的兩種解決方案:
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;
}