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

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

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


当前回答

下面是我可以构建的最好的全方位解决方案,以垂直和水平居中固定宽度、灵活高度的内容框。它已在Firefox、Opera、Chrome和Safari的最新版本中测试并运行。

.外部{显示:表格;位置:绝对;顶部:0;左:0;高度:100%;宽度:100%;}.中间{显示:表格单元格;垂直对齐:中间;}.内部{左边距:自动;右边距:自动;宽度:400px;/*你想要什么宽度*/}<div class=“outer”><div class=“middle”><div class=“inner”><h1>内容</h1><p>从前,一个沉闷的午夜</p></div></div></div>

查看动态内容的工作示例

我内置了一些动态内容来测试它的灵活性,并希望知道是否有人发现它有任何问题。它也可以很好地用于居中的覆盖——灯箱、弹出窗口等。

其他回答

这个解决方案适用于块元素(例如,<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代码演示

垂直和水平居中

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

享受

可以通过两种方式实现

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;
}

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

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

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

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

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

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