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

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

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


当前回答

可以通过两种方式实现

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>

实际上,垂直居中需要两个div。包含内容的div必须具有宽度和高度。

#集装箱{位置:绝对;顶部:50%;页边空白:-200像素;/*#内容高度的一半*/左:0;宽度:100%;}#内容{宽度:624px;左边距:自动;右边距:自动;高度:395px;边框:1px实心#000000;}<div id=“container”><div id=“content”><h1>居中的div</h1></div></div>

这是结果。

垂直和水平居中

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

享受

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

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

我最近发现了一个技巧:你需要使用前50%,然后再进行translateY(-50%)。

.外部div{位置:相对;高度:150px;宽度:150px;背景色:红色;}.居中div{位置:绝对;顶部:50%;-webkit转换:translateY(-50%);-ms变换:translateY(-50%);变换:translateY(-50%);背景色:白色;}<div class='outer-div'><div class='entered-div'>测试文本</div></div>