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

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

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


当前回答

我认为,对于所有不使用Flexbox的浏览器来说,“alignitems:center;”是一种显示:表格和垂直对齐:中间;的组合;。

CSS

.vertically-center
{
    display: table;

    width: 100%;  /* Optional */
    height: 100%; /* Optional */
}

.vertically-center > div
{
    display: table-cell;
    vertical-align: middle;
}

HTML

<div class="vertically-center">
    <div>
        <div style="border: 1px solid black;">some text</div>
    </div>
</div>

演示:https://jsfiddle.net/6m640rpp/

其他回答

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

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

这在我的情况下有效(仅在现代浏览器中测试):

.textthatneedstobecentered {
  margin: auto;
  top: 0; bottom: 0;
}

可以通过两种方式实现

body{
left: 50%; 
top:50%; 
transform: translate(-50%, -50%); 
height: 100%; 
width: 100%; 
}

OR

使用flex

body {
    height:100%
    width:100%
    display: flex;
    justify-content: center;
    align-items: center;
}

对齐项目:居中;使内容垂直居中

对齐内容:中心;使内容水平居中

这个解决方案适用于块元素(例如,<div>)。我用颜色使溶液更清晰。

HTML格式:

<main class="skin_orange">
    <p>As you can the the element/box is vertically centered</p>
    <div class="bigBox skin_blue">Blue Box</div>
</main>

CSS:

main {
    position: relative;
    width: 400px;
    height: 400px;
}

.skin_orange {
    outline: thin dotted red;
    background: orange;
}

.bigBox {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

.skin_blue {
    background-color: blue;
}

JSFiddle代码演示

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

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