因朋友网页改版后的页面内容少,要将footer层固定在整个页面的最下方,网页的内容比较少时,页脚的联系方式部分不随着页面中的内容高度的减小而上移。这种方式适用于将网页中的版权信息固定在页面下方。当然,当页面内容多时,页脚也要正常显示。
这就要用到CSS的4大核心基石:盒子模型、标准流、浮动、定位。只有把这些核心基础掌握到烂熟于胸的程度,才能游刃有余地进行设计。
设计思路:首先设置最外层的一个容器div,id设为#container,使他的高度为浏览器窗口的高度,然后将#footer这个div设置为#container的子div,并使用绝对定位,使他固定到#container的底端。代码如下,可以改变#content里面的内容的高度,查看Footer部分的显示效果。
示例文件下载:使用CSS固定页脚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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="zh-CN" /> <title>使用CSS固定页脚footer</title> </head> <body> <div id="container"> <div id="content"> <h1>Content</h1> <p>请改变示例文字的高度,查看footer显示效果。</p> <p>这里是示例文字。</p> </div> <div id="footer"> <h1>页脚Footer</h1> </div> </div> </body> </html>
然后设置CSS:
body,html { margin: 0 auto; padding: 0; font-size: 12px; font-family:Arial, Helvetica, sans-serif, monospace; height:100%; width:960px; } #container { min-height:100%; position: relative; } #content { padding:10px 0; padding-bottom: 40px; /* 注意这个红色的高度:页脚内容总高度(字体大小,行距,padding等) 避免覆盖#content的文字*/ } #footer { position: absolute; bottom: 0; padding: 10px 0; background-color: #ccc; width: 100%; } #footer h1 { font-size: 20px; margin:0; padding:0 10px; }
评论