今天遇到一個問題:使用css實現頁腳固定在底部,當內容不足一屏時,頁腳在窗口底部,當大於一屏時在整個頁面的最底部。總結兩種實現方式:css
第一種:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>頁腳固定在頁面底部</title> </head> <style type="text/css"> *{ margin: 0; padding: 0; } html,body { height: 100%; } #container { min-height:100%; height: auto !important; height: 100%; /*IE6不識別min-height*/ position: relative; } #content { width: 100%; height: 300px; margin: 0 auto; padding-bottom: 60px;/*等於footer的高度*/ } header { background-color: #080808; height: 60px; } footer { position: absolute; bottom: 0; width: 100%; height: 60px;/*腳部的高度*/ background-color: #080808; clear:both; } </style> <body> <div id="container"> <header>Header Section</header> <div id="content" class="clearfix"> 頁面容容部分 </div> <footer>Footer Section</footer> </div> </body> </html>
第二種:瀏覽器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>頁腳固定在頁面底部</title> <style type="text/css"> *{ padding: 0; margin: 0; } html, body{ height: 100%; margin:0; padding:0; } #container { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -60px;/*margin-bottom的負值等於footer高度*/ } header { height: 60px; background-color: #080808; } footer { height: 60px; clear:both; background-color: #080808; } </style> </head> <body> <div id="container"> <header>Header Section</header> <div id="page" class="clearfix"> 頁面容容部分 </div> </div> <footer>Footer section</footer> </body> </html>
這種方法是利用footer的margin-top負值來實現footer永遠固定在頁面的底部效果。spa
這兩種方式結構簡單清晰,無需js和任何hack能實現各瀏覽器下的兼容。code