方法一:footer高度固定+絕對定位
HTML結構:
<body>
<header>header</header>
<main>main content</main>
<footer>footer</footer>
</body>
CSS設置:
html{height:100%;}
body{min-height:100%;margin:0;padding:0;position:relative;}
header{background-color: #ffe4c4;}
main{padding-bottom:100px;background-color: #bdb76b;}/* main的padding-bottom值要等於或大於footer的height值 */
footer{position:absolute;bottom:0;width:100%;height:100px;text-align: center;background-color: #ffc0cb;}
首先,設置body的高度至少充滿整個屏幕,並且body作爲footer絕對定位的參考節點;
其次,設置main(footer前一個兄弟元素)的padding-bottom值大於等於footer的height值,以保證main的內容能夠全部顯示出來而不被footer遮蓋;
最後,設置footer絕對定位,並設置height爲固定高度值
。
方法二:footer高度固定+margin負值
HTML結構:
<body>
<div class="container">
<header>header</header>
<main>main content</main>
</div>
<footer>footer</footer>
</body>
CSS設置:
html,body{height:100%;margin:0;padding:0;}
.container{min-height:100%;}
header{background-color: #ffe4c4;}
main{padding-bottom:100px;background-color: #bdb76b;}/* main的padding-bottom值要等於或大於footer的height值 */
footer{height:100px;margin-top:-100px;background-color: #ffc0cb;}/* margin-top(負值的)高度等於footer的height值 */
此方法把footer之前的元素放在一個容器裏面,形成了container和footer並列的結構:
首先,設置.container的高度至少充滿整個屏幕;
其次,設置main(.container最後一個子元素)的padding-bottom值大於等於footer的height值;
最後,設置footer的height值和margin-top負值
。
這種方法沒有使用絕對定位,但html結構的語義化不如方法一中的結構清晰。
也可以設置負值的margin-bottom在.container上面,此時html結構變化如下:
<body>
<div class="container">
<header>header</header>
<main>main content</main>
<div class="empty"></div>
</div>
<footer>footer</footer>
</body>
CSS設置:
html,body{height:100%;margin:0;padding:0;}
.container{min-height:100%;margin-bottom:-100px;}
.empty,footer{height:100px;}
使用一個空的div把footer容器推到頁面最底部,同時給container設置一個負值的margin-bottom,這個margin-bottom與footer和.empty的高度相等。
雖然多了一個空的div,語義上也不怎麼好,但是相比前面爲main元素設置padding-bottom的方法有一個明顯的好處:當網頁內容不滿一屏的時候,如果需要爲main元素設置邊框、背景色的時候,padding-bottom硬生生地撐出了一片空白,真真是有點醜,但是加個空的div之後,佈局方式作用在.empty上,對main的css設置就不影響了,算是一個好處吧!
方法三:footer高度任意+js
HTML結構:
<body>
<header>header</header>
<main>main content</main>
<footer>footer</footer>
</body>
CSS設置:
html,body{margin:0;padding: 0;}
header{background-color: #ffe4c4;}
main{background-color: #bdb76b;}
footer{background-color: #ffc0cb;}
/* 動態爲footer添加類fixed-bottom */
.fixed-bottom {position: fixed;bottom: 0;width:100%;}
js代碼:
$(function(){
function footerPosition(){
$("footer").removeClass("fixed-bottom");
var contentHeight = document.body.scrollHeight,//網頁正文全文高度
winHeight = window.innerHeight;//可視窗口高度,不包括瀏覽器頂部工具欄
if(!(contentHeight > winHeight)){
//當網頁正文高度小於可視窗口高度時,爲footer添加類fixed-bottom
$("footer").addClass("fixed-bottom");
}
}
footerPosition();
$(window).resize(footerPosition);
});