<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用CSS定位页面的“footer”</title>
<style type="text/css">
<!--
body,html {
margin: 0;
padding: 0;
font: 12px/1.5 arial;
height:100%;
}
#container {
min-height:100%;
position: relative;
}
#content {
padding: 10px;
padding-bottom: 60px;
/* 20px(font-size)x2(line-height) + 10px(padding)x2=60px*/
}
#footer {
position: absolute;
bottom: 0;
padding: 20px 0;
background-color: #AAA;
width: 100%;
height:20px;
}
#footer h1 {
font: 20px/2 Arial;
margin:0;
padding:0 10px;
}
-->
</style></head>
 
<body>
<div id="container">
    <div id="content">
          <h1>Content</h1>
          <p>请改变浏览器窗口的高度,以观察footer效果。</p>
          <p>1:首先要给 html 和 body 元素设置高度(height属性)为100% (第5行),这样先保证根元素的高度撑满整个浏览器窗口,然后下面才能使 #container 的高度撑满整个浏览器窗口。至于为什么用同时设置 html 和 body 元素,是因为 Firefox 和 IE 认为的根元素不一样,因此这里都给他们设置上。
</p>
2:然后把 #container 的高度也设置为 100% (第8行),但是要注意,这里使用了“min-height”属性,而不是普通的 height 属性,这是因为我们要考虑到,如果 #content 中的内容如果增加了,他的高度超过了浏览器窗口的高度,那么如果把 #container 的高度仍然是 100%,就会导致 #footer 仍然定位在浏器窗口的下端,从而遮盖了 #content 中的内容。而使用 min-height 属性的作用就是使 #container 的高度“至少”为浏览器窗口的高度,而当如果它里面的内容增加了,他的高度会也跟随着增加,这才是我们需要的效果。
<p>
但是需要说明的是,在 Firefox 和 IE7 中,支持 min-height 属性,而 IE6 中,并不支持 min-height 属性,但是“歪打正着”的是,IE6 中,会把 min-height 属性解释为 height 属性,但是 IE6 中 height 属性的效果却是 min-height 本来应该具有的效果,也就是说,在 IE6 中,子 div 的高度会撑大父 div 的高度。所以这样正好可以实现在 IE6、IE7 和 Firefox 中都可以正确实现我们希望的效果了。
</p>
3:接下来,将 #container 设置为相对定位(第9行),目的是使他成为它里面的 #footer 的定位基准,也就是所谓的“最近的定位过的祖先元素”。
<p>
4:然后把 #foooter 设置为绝对定位(第17行),并使之贴在 #container 的最下端(第18行)。
</p>
5:但是要注意,如果当我们把 #foooter 贴在 #container 的最下端以后,他实际上已经和上面的 #content 这个div 重叠了,为了避免覆盖 #content 中的内容,我们在 #contetn 中设置了下侧的 padding,使 padding-bottom 的值等于 #footer 的高度(第13行),就可以保证避免覆盖 #content 的文字了,这个高度的计算注意代码中的注释中给出的计算方法(第14行)。
    </div>
    <div id="footer">
        <h1>Footer</h1>
    </div>
</div>
 
</body>
</html>