用css实现footer

在html页面中,footer是非常有用,我们用它来标识它的版权和页面的相关信息。比如淘宝指数中的版权信息

它的一个特点就是会“固定”在页面的尾部,并不会随这页面主内容少而跑上面去,当页面内容过多,超过一屏幕时,会紧跟在内容尾部,具体效果如图(来自网络):

那怎么实现呢?其实很简单,只用设置css样式即可。

第一种方法

HTML代码

<div id="container">
  <div id="header">Header Section</div>
  <div id="body" class="clearfix">
    页面容容部分
  </div>
  <div id="footer">Footer Section</div>
</div>

CSS代码

html,body {
  margin: 0;
  padding:0;
  height: 100%;
}
#container {
  min-height:100%;
  height: auto !important;
  height: 100%; /*IE6不识别min-height*/
  position: relative;
}
#body {
  width: 960px;
  margin: 0 auto;
  padding-bottom: 60px;/*等于footer的高度*/
}
#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px;/*脚部的高度*/
  clear:both;
}

优点:
结构简单清晰,无需js和任何hack能实现各浏览器下的兼容,同时在ipad、iphone下也可以正常运行

缺点:

1. 需要给div#footer容器设置一个固定高度
2. 需要将div#page容器的padding-bottom设置大于等于div#footer的高度

参考: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page
DEMO: http://matthewjamestaylor.com/blog/bottom-footer-demo.htm

第二种方法

利用footer的margin-top负值来实现footer永远固定在页面的底部效果,原理和效果跟第一种方法是一样的

HTML代码

<div id="container">
  <div id="header">Header Section</div>
  <div id="page">Main Content</div>
</div>  
<div id="footer">footer</div>

CSS代码

html,body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#container {
  min-height: 100%;
  height: auto !important;
  height: 100%;
}
#footer {
  position: relative;
  margin-top: -60px;/*等于footer的高度*/
  height: 60px;
  clear:both;
}
#page {
  padding-bottom: 60px;/*高度等于footer的高度*/
}

  第三种方法 

HTML代码

<div id="container">
    <div id="page"> Content </div>
    <div class="push"> 空标签</div>
  </div>
<div id="footer">Footer</div>

 CSS代码

html,body{
  height: 100%;
  margin:0;
  padding:0;
}
#container {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  margin: 0 auto -60px;/*margin-bottom的负值等于footer高度*/
}
.push, #footer {
  height: 60px;
  clear:both;
}

优点:

简单明了,易于理解,兼容所有浏览器。

缺点:

1.较之前面的两种方法,多使用了一个div.push容器

2.同样此方法限制了footer部分高度,无法达到自适应高度效果。

这种方法并不推荐使用

参考:
http://ryanfait.com/resources/footer-stick-to-bottom-of-page/

补充:现在html5中已经增加了footer标签,在适当情况可以善用这个标签

声明:这篇文章并非完全原创,而且根据我同事田超强的分享文章整理所得。

原文地址:https://www.cnblogs.com/lengyuhong/p/2998095.html