將footer固定在頁面底部的實現方法
來自: https://segmentfault.com/a/1190000004453249
方法一: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;background-color: #ffc0cb;}</pre>
首先,設置body的高度至少充滿整個屏幕,并且body作為footer絕對定位的參考節點;
其次,設置main(footer前一個兄弟元素)的padding-bottom值大于等于footer的height值,以保證main的內容能夠全部顯示出來而不被footer遮蓋;
最后,設置footer絕對定位,并 設置height為固定高度值 。
</div>
方法二: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值 /</pre>
此方法把footer之前的元素放在一個容器里面,形成了container和footer并列的結構:
首先,設置.container的高度至少充滿整個屏幕;
其次,設置main(.container最后一個子元素)的padding-bottom值大于等于footer的height值;
最后,設置footer的height值和 margin-top負值 。
</div>
這種方法沒有使用絕對定位,但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%;}</pre>
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");
} else {
$("footer").removeClass("fixed-bottom");
}
}
footerPosition();
$(window).resize(footerPosition);
}); </div>
本文由用戶 nanlingcg 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
相關經驗
相關資訊