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

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

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


当前回答

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

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

其他回答

我最近发现了一个技巧:你需要使用前50%,然后再进行translateY(-50%)。

.外部div{位置:相对;高度:150px;宽度:150px;背景色:红色;}.居中div{位置:绝对;顶部:50%;-webkit转换:translateY(-50%);-ms变换:translateY(-50%);变换:translateY(-50%);背景色:白色;}<div class='outer-div'><div class='entered-div'>测试文本</div></div>

我觉得这个最有用。。。它给出了最准确的“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;
}

这里有一个简单的方法,几乎没有代码:

CSS代码:

.main{
    height: 100%;
}

.center{
    top: 50%;
    margin-top: 50%;
}

HTML代码:

<div class="main">
    <div class="center">
        Hi, I am centered!
    </div>
</div>

您的文本将位于页面中间!

实际上,垂直居中需要两个div。包含内容的div必须具有宽度和高度。

#集装箱{位置:绝对;顶部:50%;页边空白:-200像素;/*#内容高度的一半*/左:0;宽度:100%;}#内容{宽度:624px;左边距:自动;右边距:自动;高度:395px;边框:1px实心#000000;}<div id=“container”><div id=“content”><h1>居中的div</h1></div></div>

这是结果。

不幸的是,但并不令人惊讶的是,解决方案比人们希望的更复杂。同样不幸的是你需要在垂直居中的div周围使用额外的div。

对于符合标准的浏览器,如Mozilla、Opera、Safari等,您需要将外部div设置为显示为表,将内部div设置为表单元格-然后可以垂直居中。对于InternetExplorer,您需要将内部div绝对放置在外部div中,然后将顶部指定为50%。以下页面很好地解释了这一技术,并提供了一些代码示例:

CSS中的垂直居中未知高度的CSS垂直居中(兼容Internet Explorer 7)(Wayback Machine提供的存档文章)

还有一种使用JavaScript进行垂直居中的技术。内容与JavaScript和CSS的垂直对齐演示了这一点。