将容器垂直对齐

时间:2011-06-03 13:22:05

标签: html css vertical-alignment

我想将容器div垂直对齐,就像margin: auto;因为水平对齐一样。我在谷歌搜索了一些关于如何做到这一点的时间,但它似乎并不适合我。也许有某种通用的方法可以做到这一点,就像水平居中的margin: auto;方法一样简单?因为我觉得很奇怪,我们生活在2011年,并且仍然没有简单的css命令来完成这项任务......

#container
{
    margin: auto;
    width: 960px;
    height: 640px;
    background-color: brown;
}

screenshot

3 个答案:

答案 0 :(得分:2)

垂直对齐有tons of tutorials,特别是IE,需要特别小心。其中之一:Vertically center content with CSS。还有另一个答案here

答案 1 :(得分:1)

如果你的div有一个固定的高度,你可以通过添加另一个带有负边距(主div的高度的一半)的div(带浮动)来垂直对齐,然后改变div的CSS(添加{{1 }})。

另外,请不要忘记指定clearhtml的100%高度,但不会失效。

像这样:

<强> CSS

body

<强> HTML

html {
    overflow: auto;
}
html, body {
    margin:0;
    padding:0;
    height:100%;
}
#alignDiv {
    float:left;
    height:50%;
    margin-bottom:-320px; /* half the centered div */
    width:1px;
}
#container
{
    margin: 0 auto;
    width: 960px;
    height: 640px;
    background-color: brown;
    clear:left; /* without the clear it won't center */
}

答案 2 :(得分:0)

它可以更简单......

html, body {
    overflow:hidden
}
#container {
    width:960px;
    height:640px;
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-320px;
    margin-left:-480px;
    background:brown
}

overflow:hidden用于隐藏显示的滚动条(IE6为html,IE5为body。我不知道为什么会这样。

但如果你想在浏览器窗口较小的情况下保持滚动,只需将高度设为639px并移除overflow:hidden