今天遇到一个问题:使用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