如何将页脚固定在页面底部

html-css031

如何将页脚固定在页面底部,第1张

注意了这里所说的是页脚footer永远固定在页面的底部,而不是永远固定在显示器屏幕的底部,换句话说,就是当内容只有一点点时,Web页面显示在浏览器底部,当内容高度超过浏览器高度时,Web页面的footer部分在页面的底部,总而言之Web页面的footer部分永远在页面的底部,换句说,Footer部分永远沉底。如下图所示:

那么今天主要和大家一起学习如何将页脚固定在页面的底部?

方法一:

首先我们来看第一种方法,这种方法是来自于Matthew James Taylor的《How to keep footers at the bottom of the page》。下面我们就一起来看看Matthew James Taylor介绍的方法。

<div id="container">

<div id="header">Header Section</div>

<div id="page" class="clearfix">

页面容容部分

</div>

<div id="footer">Footer Section</div>

</div>

其实我们可以在div#page增加所需的内容结构,如下所示:

<div id="container">

<div id="header">Header Section</div>

<div id="page" class="clearfix">

<div id="left">Left Sidebar</div>

<div id="content">Main content</div>

<div id="right">Right sidebar</div>

</div>

<div id="footer">Footer Section</div>

</div>

真正来说,实现这页脚永远固定在页面的底部,

我们只需要四个div,其中div#container是一个容器,在这个容器之中,我们包含了div#header(头部),div#page(页面主

体部分,我们可以在这个div中增加更多的div结构,如上面的代码所示),div#footer(页脚部分)

html,body {

margin: 0

padding:0height: 100%

}

#container {

min-height:100%

height: auto !important

height: 100%/*IE6不识别min-height*/

position: relative

}

#header {

background: #ff0

padding: 10px

}

#page {

width: 960px

margin: 0 auto

padding-bottom: 60px/*等于footer的高度*/

}

#footer {

position:

absolute

bottom: 0

width: 100%

height: 60px/*脚部的高度*/ background: #6cf

clear:both

}

/*=======主体内容部分=======*/

#left {

width: 220px

float: left

margin-right: 20px

background: lime

}

#content {

background: orange

float: left

width: 480px

margin-right: 20px

}

#right{

background: green

float: right

width: 220px

}

下面我们一起来看看这种方法的实现原理:

1. <html>和<body>标签:html和body标签中必须将高度(height)设置为“100%”,这样我们就可以在容器上设置百分比高度,同时需要将html,body的margin和padding都移除,也就是html,body的margin和padding都为0;

2. div#container容器:div#container容器必须设置一个最小高度(min-

height)为100%;这主要使他在内容很少(或没有内容)情况下,能保持100%的高度,不过在IE6是不支持min-height的,所以为了兼

容IE6,我们需要对min-height做一定的兼容处理,具体可以看前面的代码,或者阅读Min-Height Fast Hack了解如何解决min-height在Ie6下的bug问题。另外我们还需要在div#container容器中设置一个”position:relative”以便于里面的元素进行绝对定位后不会跑了div#container容器;

3. div#page容器:div#page这个容器有一个很关键的设

置,需要在这个容器上设置一个padding-bottom值,而且这个值要等于(或略大于)页脚div#footer的高度(height)值,当然你

在div#page中可以使用border-bottom人水-width来替代padding-bottom,但有一点需要注意,此处你千万不能使用margin-bottom来代替padding-bottom,不然会无法实现效果;

4. div#footer容器:div#footer容器必须设置一个固定高度,单位可以是px(或em)。div#footer还需要进行绝对定位,并且设置bottom:0;让div#footer固定在容器div#container的底部,这样就可以实现我们前面所说的效果,当内容只有一点时,div#footer固定在屏幕的底部(因为div#container设置了一个min-height:100%),当内容高度超过屏幕的高度,div#footer也固定在div#container底部,也就是固定在页面的底部。你也可以给div#footer加设一个”width:100%”,让他在整个页面上得到延伸;

5. 其他div:至于其他容器可以根据自己需求进行设置,比如说前面的div#header,div#left,div#content,div#right等。

优点:

结构简单清晰,无需js和任何hack能实现各浏览器下的兼容,并且也适应iphone。

缺点:

不足之处就是需要给div#footer容器设置一个固定高度,这个高度可以根据你的需求进行设置,其单位可以是px也可以是em,而且还需要将

div#page容器的padding-bottom(或border-bottom-width)设置大小等于(或略大于)div#footer的高

度,才能正常运行。

<div>正文</div>

<div>页脚</div>

html结构上页脚在正文下面,那么不用任何css它本身就是在下面的,你多半是企图用定位来布局整个页面,然后就重叠了。