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

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

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


当前回答

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

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

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

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

特别是对于具有相对(未知)高度的父div,未知解决方案中的居中对我来说非常有用。

它在Chrome、Firefox、Opera和Internet Explorer中进行了测试。

/*此父项可以是任何宽度和高度*/.块{文本对齐:居中;}/*鬼魂被推着保持完美的居中*/.block:之前{内容:“”;显示:内联块;高度:100%;垂直对齐:中间;右边距:-0.25em;/*调整间距*/}/*要居中的元素可以也可以是任何宽度和高度*/.居中{显示:内联块;垂直对齐:中间;宽度:300px;}<div style=“width:400px;height:200px;”><div class=“block”style=“高度:90%;宽度:100%”><div class=“center”><h1>一些文本</h1><p>任何其他文本。。。“”</p></div></div></div>

使用CSS Flexbox align items属性来实现这一点。

html,正文{高度:100%;}正文{显示:柔性;对齐项目:居中;}<div>垂直居中</div>

实现这一点有多种方法。

使用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>