无法居中<div>元素</div>

时间:2012-05-13 14:01:54

标签: html css

我尝试将div元素(在这种情况下为页脚div)放在我的网页中心,但它坚持留在左侧。

我不太确定有什么问题......有什么想法吗? 提前谢谢。

HTML:

<div id='main'>
</div>

<div id='footer'>Centered Text</div>​

CSS:

* {
    padding: 0;
    margin:  0;
    font-size:   12px;
}

body {
    font-family: helvetica, serif;
    font-size:   12px;
    overflow-y:scroll;
}

#main {
    border: 1px solid #bbbbbb;
    margin: 3% 5%;
    padding: 10px 10px;
}

#footer {
    font-size: 75%;
    margin: 0px auto;
    position: absolute;
    bottom: 0px;
}

http://jsfiddle.net/DjPjj/2/

2 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/DjPjj/13/

试试这个:

#footer {
    font-size: 75%;
    width: 100%;
    position: absolute;
    bottom: 0px;
    text-align: center;
}

由于您的页脚是绝对定位的,您必须告诉它相对于其父容器的宽度。然后,您可以使用text-align将文本居中放置。

这是另一个例子:http://jsfiddle.net/DjPjj/17/

这个盒子在绝对定位的元素中居中。内框可以使用margin: 0 auto居中,因为它没有绝对定位。

#footer {
    font-size: 75%;
    width: 100%;
    position: absolute;
    bottom: 0px;
}

#footerInner {
  margin: 0 auto;
  width: 300px;
  background-color: #ddd;
  text-align: center;
}

这更灵活,因为内部元素为您提供了一个新的容器,可以使用相对于父级居中的容器。

答案 1 :(得分:1)

它不会居中的原因是因为positon: absolute;

请记住,这意味着页脚将始终位于页面底部,即使内容溢出也是如此。它会重叠。如果要将其附加到页面底部,则必须将其上方容器的最小高度设置为100%,然后处理负边距顶部并删除position: abosolute;

http://jsfiddle.net/4fuk7/1/

注意如何覆盖居中文本。

如果您正在寻找始终位于底部的东西,这将有效 http://jsfiddle.net/4fuk7/3/

抱歉,最后一个会滚动到顶部。这个没有,但你需要稍微调整它以使其正确对齐你设置的边距。 http://jsfiddle.net/4fuk7/9/ http://www.tlunter.com/Layout 2 /是我做过类似事情的地方。如果需要,可以参考。