相信很多前端工程師在開發頁面時會遇到這個情況:當整個頁面高度不足以占滿顯示屏一屏,頁腳不是在頁面最底部,用戶視覺上會有點不好看,想讓頁腳始終在頁面最底部,我們可能會想到用:
1.min-height來控制content中間內容區高度來讓頁面高度能夠占滿顯示屏一屏,但是大型網站頁面比較多的情況下footer都是模塊化添加進去的,每個頁面高度都不會一樣,不可能去設置每個頁面中間內容區min-height高度,而且用戶的顯示屏的大小都不一樣,無法精確設置min-height高度,無法保證用戶看到頁面頁腳不是在最底部或頁面不出現滾動條;
2.頁腳固定定位:頁腳相對於body固定定位會顯示在最底部,但是頁面有滾動條時,頁面滾動,頁腳會懸浮在內容區上,可能以上都不是你想要的效果。
可以用下實例方法解決你的問題:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>猿來是勇者</title> </head> <!--方法一--> <style> *{margin: 0; padding: 0;} html,body{height:100%;} #container{position:relative; width:100%; min-height:100%;padding-bottom: 100px; box-sizing: border-box;} header{width: 100%; height: 200px; background: #999;} .main{width: 100%; height: 200px; background: orange;float:left;} footer{width: 100%; height:100px; /* footer的高度一定要是固定值*/ position:absolute; bottom:0px; left:0px; background: #333;} </style> <body> <div id="container"> <header>HEADER</header> <section class="main">MAIN</section > <footer>FOOTER</footer> </div> </body> <!--方法二--> <!--<style> *{margin: 0; padding: 0;} html,body{height: 100%;} #container{display: flex; flex-direction: column; height: 100%;} header{background: #999; flex: 0 0 auto;height:100px;} .main{flex: 1 0 auto;} .bg{background:orange;height:200px;} footer{background: #333; flex: 0 0 auto;height:100px;} </style> <body> <div id="container"> <header>HEADER</header> <section class="main"> <div class="bg">MAIN</div> </section> <footer>FOOTER</footer> </div> </body>--> </html>