解決Web開發HTML頁面中footer保持在頁面底部問題


如圖所示如何實現footer在內容不足或者瀏覽器窗口變大變小的時候一直保持在底部呢?請看如下兩種解決方案。

第一種方案:

footer高度固定+絕對定位 (兼容性比較好完美兼容IE8+)
思路:footer的父層的最小高度是100%,footer設置成相對於父層位置絕對(absolute)置底(bottom:0),父層內要預留(padding-bottom)footer的高度。

HTML

<div class="wrapper">
    <div class="header">頭部</div>
    <div class="main">內容</div>
    <div class="footer">底部</div>
</div>

CSS

*{
    margin: 0;
    padding: 0;
}
html,body{
    height: 100%;
}
.wrapper{
    /*保證footer是相對於container位置絕對定位*/
    position:relative;  
    width:100%;
    min-height:100%; 
    /*設置padding-bottom值大於等於footer的height值,以保證main的內容能夠全部顯示出來而不被footer遮蓋;*/  
    padding-bottom: 100px;  
    box-sizing: border-box;
}
.header{
    width: 100%;
    height: 200px;
    background: #999;
}
.main{
    width: 100%;
    height: 200px;
    background: orange;
}
.footer{
    width: 100%;
    height:100px;   /* footer的高度一定要是固定值*/ 
    position:absolute;
    bottom:0px;
    left:0px;
    background: #333;
}

如果在main區域設置了浮動啥的你會發現footer固定在頁面可視區的底部,且覆蓋在內容上,這時候只要在footer的父元素樣式上增加(overflow : hidden;)即可;

第二種方案:

采用 flexbox布局模型 
思路:我們將 body 的 display 屬性設置為 flex, 然后將方向屬性設置為列, (默認是行,也就是橫向布局);同時,將html 和 body 元素的高度設置為100%,使其充滿整個屏幕。 
HTML

<div class="wrapper">
    <div class="header">頭部</div>
    <div class="main">內容</div>
    <div class="footer">底部</div>
</div>

CSS
我們需要調整各個區域占用的頁面空間,我們將通過flex 屬性來達到這一目的,該屬性實際包含了三個屬性,分別是:
(1)flex-grow:元素在同一容器中對可分配空間的分配比率,及擴展比率;
(2)flex-shrink:如果空間不足,元素的收縮比率;
(3)flex-basis:元素的伸縮基准值;

*{
    margin: 0;
    padding: 0;
}
html,body{
    height: 100%;
}
.wrapper{
    display: flex;
    flex-direction: column;
    height: 100%;
}
.header{
    background: #999;
    flex: 0 0 auto;
}
.main{
    background: orange;
    flex: 1 0 auto;
}
.footer{
    background: #333;
    flex: 0 0 auto;
}

 

原文鏈接:https://blooo.cn/article/10


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM