Sticky footer布局是什么?
我們所見到的大部分網站頁面,都會把一個頁面分為頭部區塊、內容區塊和頁腳區塊,當頭部區塊和內容區塊內容較少時,頁腳能固定在屏幕的底部,而非隨着文檔流排布。當頁面內容較多時,頁腳能隨着文檔流自動撐開,顯示在頁面的最底部,這就是Sticky footer布局。
圖示說明
- 當內容較少時,正常的文檔流效果如下圖

在正常的文檔流中,頁面內容較少時,頁腳部分不是固定在視窗底部的,這時就要用到Stickyfooter布局。
- Sticky footer布局效果如下圖

這樣就符合我們的預期效果,可以看出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-bottom、footer元素的高度以及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布局是十分常見的一種頁面布局形式,實現的方法也比較多,以上兩種方法最為常用,且基本可以滿足所有應用場景。
