问题描述:
在页面中可能有这样的footer,我们期望它永远在页面的最下方。
当页面高度足够的时候,始终保持与浏览器底边有一定得距离:
如果仅是设置footer的style="position:absolute;bottom:10px",当浏览器高度小于内容高度时,footer就会覆盖住内容。如下图:
我们所期望的是当浏览器高度不足时,footer依然位于"内容"的下方,拖动滚动条才能显示。
解决方案:
完整html代码如下,
-------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB">
<head>
<title>example</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<style type="text/css">
html, body {
margin:0; /* 必要,否则纵向滚动条不会消失 */
height:100%; /* 必要,以便之后给container设置高度百分比 */
}
#container {
min-height:100%; /* 此属性需要doctype的支持,见第一行。 否则不会生效。在IE中,写height:100%就可以工作,但其他浏览器需要设置min-height。*/
position:relative; /* 必要 */
}
#body {
padding-bottom:50px; /* 等于footer的高度 */
height:200px;
border:solid 1px red;
}
#footer {
position:absolute; /* 必要 */
bottom:0; /* 必要 */
height:50px
}
</style>
</head>
<body>
<div id="container">
<div id="body">
blah....
</div>
<div id="footer">
I am footer!
</div>
</div>
</body>
</html>
-------------------------------------------------------------------
如果使用的doctype不支持min-height,以上代码在firefox中仍可工作,但在IE中失效。解决办法如下:
-------------------------------------------------------------------
#container {
*height:100%; /* “*”使这句只在ie中生效 */
min-height:100%; /* 对firefox生效 */
position:relative;
}
其他代码与方案1相同。
-------------------------------------------------------------------
参考文章:
1, http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page
2, http://ryanfait.com/resources/footer-stick-to-bottom-of-page/