1. 程式人生 > 其它 >《解決HTML中footer保持在頁面底部問題》

《解決HTML中footer保持在頁面底部問題》

頁面內容太少,無法將內容區域撐開,從而在 footer 下面留下一大塊空白;但是我們又希望footer能在視窗最底端。兩種方法來解決這個問題:

方法一:footer高度固定+絕對定位

思路:footer的父層的最小高度是100%,footer設定成相對於父層位置絕對(absolute)置底(bottom:0),父層內要預留(padding-bottom)footer的高度。
HTML程式碼:

<div id="container">
<header>HEADER</header>
<section class="main">MAIN</section >
<footer>FOOTER</footer>
</div>

CSS程式碼:

*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
}
#container{
/*保證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 id="container">
<header>HEADER</header>
<section class="main">MAIN</section>
<footer>FOOTER</footer>
</div>

CSS程式碼:

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

*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
}
#container{
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;
}

————————————————