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

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

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


当前回答

对于新手,请尝试:

display: flex;
align-items: center;
justify-content: center;

其他回答

我觉得这个最有用。。。它给出了最准确的“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;
}
.center{
    display: grid;
    place-items: center;
}

名单上还有一个我看不到的:

.Center-Container {
  position: relative;
  height: 100%;
}

.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  border: solid black;
}

跨浏览器(包括Internet Explorer 8-Internet Explorer 10,无黑客攻击!)响应百分比和最小值/最大值-居中,不考虑填充(不考虑框大小!)必须声明高度(请参见可变高度)建议设置溢出:自动防止内容溢出(请参阅溢出)

来源:CSS中的绝对水平和垂直居中

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

CSS代码:

.main{
    height: 100%;
}

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

HTML代码:

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

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

使用Flexbox可以轻松将内容居中。以下代码显示了容器的CSS,其中的内容需要居中:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;
}