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

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

如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置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;
}

其他回答

我这样做了(相应地改变宽度、高度、顶部边距和左侧边距):

.wrapper {
    width: 960px;
    height: 590px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -295px;
    margin-left: -480px;
}
<div class="wrapper"> -- Content -- </div>

此方法不使用任何变换。因此,输出变得模糊没有问题。

position: absolute;
width: 100vw;
top: 25%;
bottom: 25%;
text-align: center;

我只是找到了另一种对我有用的方法:

<div class="container">
  <div class="vertical">
     <h1>Welcome</h1>
     <h2>Aligned Vertically</h2>
     <a href="#">Click ME</a>
   </div>
</div>

CSS

.vertical{
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

更多信息

垂直和水平居中

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 */}

享受

实现这一点有多种方法。

使用CSS的flex属性。

解决方案#1.父级{宽度:400px;高度:200px;背景:蓝色;显示:柔性;对齐项目:居中;对齐内容:中心;}.儿童{宽度:75px;高度:75px;背景:黄色;}<div class=“parent”><div class=“child”></div></div>

或使用display:flex;边距:自动;

解决方案#2.父级{宽度:400px;高度:200px;背景:蓝色;显示:柔性;}.儿童{宽度:75px;高度:75px;背景:黄色;边距:自动;}<div class=“parent”><div class=“child”></div></div>

显示文本中心

解决方案#3.父级{宽度:400px;高度:200px;背景:黄色;显示:柔性;对齐项目:居中;对齐内容:中心;}<div class=“parent”>中心</div>

使用百分比(%)高度和宽度。

解决方案#4.父级{位置:绝对;高度:100%;宽度:100%;背景:蓝色;显示:柔性;对齐项目:居中;对齐内容:中心;}.儿童{宽度:75px;高度:75px;背景:黄色;}<div class=“parent”><div class=“child”></div></div>