css如何定位网站的footer

首先我们要在外层设定一个DIV(content <---名字可以随便定义,),让这个DIV的高度等于浏览器的高度,然后将footer这个DIV设定为content的一个子DIV ,并使用绝对定位,使它固定到content的底端;这是大概的思路,

<!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>无标题文档</title>
<style>
body,html {
margin: 0;
padding: 0;
font: 12px/1.5 arial;
height:100%;
}
#content {
min-height:100%;
position: relative;
}
#main {
padding: 10px;
padding-bottom: 60px;   /* 20px(font-size)x2(line-height) + 10px(padding)x2=60px*/
}
#footer {
position: absolute;
bottom: 0;
padding: 10px 0;
background-color: #AAA;
width: 100%;
}
#footer h1 {
font: 20px/2 Arial;
margin:0;
padding:0 10px;
}
</style>
</head>

<body>
<div id="content">
               <div id="main">
                      <h1>main</h1>
                      <p>你可以改变浏览器窗口的高度,来观察footer效果。</p>
                      <p>文字文字文字文字文字文字文字文字文字文字</p>
              </div>
              <div id="footer">
                      <h1>Footer</h1>
              <div>
          </div>
</body>
</html>

首先把HTML和BODY的HEIGHT属性设为100%;保证content的高度能撑满浏览器;

   然后把#content的高度也设置为100% ,但是这里我们使用了“min-height”属性,而不是的height属性,这是因为如果#main中的内容如果增加了,他的高度超过了浏览器窗口的 高度,那么如果把#content的高度仍然是100%,就会导致#footer仍然定位在浏器窗口的下端,从而遮盖了#content中的内容。

   而使用min-height属性的作用就是使#content的高度“至少”为浏览器窗口的高度,而当如果它里面的内容增加了,他的高度会也跟随着增加,这才是我们需要的效果。

   接下来,将#content设置为相对定位,目的是使他成为它里面的#footer的定位基准

   然后把#foooter设置为绝对定位,并使之贴在#main的最下端。

   但是要注意,如果当我们把#footer贴在#content的最下端以后,他实际上已经和上面的#main这个div重叠了,为了避免覆盖#main中 的内容,我们在#main中设置了下侧的padding,使padding-bottom的值等于#footer的高度,就可以保证避免覆盖#main的 文字了

原文地址:https://www.cnblogs.com/webqiand/p/4500561.html