我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。

<body>
    <div>Div to be aligned vertically</div>
</body>

如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?


当前回答

最简单的解决方案如下:

.外部div{宽度:100%;高度:200px;显示:柔性;边框:1px实心#000;}.内部div{边距:自动;文本对齐:居中;边框:1px纯红色;}<div class=“outer div”><div class=“inner div”>嘿!</div></div>

其他回答

最简单的解决方案如下:

.外部div{宽度:100%;高度:200px;显示:柔性;边框:1px实心#000;}.内部div{边距:自动;文本对齐:居中;边框:1px纯红色;}<div class=“outer div”><div class=“inner div”>嘿!</div></div>

经过大量研究,我终于找到了最终的解决方案。它甚至适用于浮动元素。查看源

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%); /* or try 50% */
}

我觉得这个最有用。。。它给出了最准确的“H”布局,并且非常容易理解。

这种标记的好处是您可以在一个地方定义内容大小->“PageContent”。

页面背景的颜色及其水平边距在其相应的div中定义。

<div id="PageLayoutConfiguration"
     style="display: table;
     position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
     width: 100%; height: 100%;">

    <div id="PageBackground"
         style="display: table-cell; vertical-align: middle;
         background-color: purple;">

        <div id="PageHorizontalMargins"
             style="width: 100%;
             background-color: seashell;">

            <div id="PageContent"
                 style="width: 1200px; height: 620px; margin: 0 auto;
                 background-color: grey;">

                 My content goes here...

            </div>
        </div>
    </div>
</div>

这里用CSS分隔:

<div id="PageLayoutConfiguration">
     <div id="PageBackground">
          <div id="PageHorizontalMargins">
               <div id="PageContent">
                     my content goes here...
               </div>
          </div>
     </div>
</div>
#PageLayoutConfiguration{
   display: table;
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0px;
   right: 0px;
   bottom: 0px;
   left: 0px;
}

#PageBackground{
   display: table-cell;
   vertical-align: middle;
   background-color: purple;
}

#PageHorizontalMargins{
   width: 100%;
   background-color: seashell;
}
#PageContent{
   width: 1200px;
   height: 620px;
   margin: 0 auto;
   background-color: grey;
}

使用转换的三行代码实际上在现代浏览器和Internet Explorer上运行:

.element{
     position: relative;
     top: 50%;
     transform: translateY(-50%);
     -moz-transform: translateY(-50%);
     -webkit-transform: translateY(-50%);
     -ms-transform: translateY(-50%);
}

我添加这个答案是因为我发现这个答案的前一个版本有些不完整(堆栈溢出不允许我简单地评论)。

如果当前div位于主体中且没有容器div,则“position”relative会破坏样式。然而,“fixed”似乎有效,但它显然会修复视口中心的内容此外,我使用这种样式对一些覆盖div进行了居中设置,并发现在Mozilla中,这个转换后的div中的所有元素都失去了底部边框。可能是渲染问题。但是,只在其中一些页面上添加最小的填充就可以正确地渲染。Chrome和Internet Explorer(令人惊讶)渲染了这些框,而不需要填充

垂直和水平居中

HTML

<div id="dialog">Centered Dialog</div>

CSS

#dialog {
    position:fixed; top:50%; left:50%; z-index:99991;
    width:300px; height:60px;
    margin-top:-150px;  /* half of the width */
    margin-left:-30px; /* half of the height */}

享受