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

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

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


当前回答

最简单的解决方案如下:

.外部div{宽度:100%;高度:200px;显示:柔性;边框:1px实心#000;}.内部div{边距:自动;文本对齐:居中;边框:1px纯红色;}<div class=“outer div”><div class=“inner div”>嘿!</div></div>

其他回答

名单上还有一个我看不到的:

.Center-Container {
  position: relative;
  height: 100%;
}

.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  border: solid black;
}

跨浏览器(包括Internet Explorer 8-Internet Explorer 10,无黑客攻击!)响应百分比和最小值/最大值-居中,不考虑填充(不考虑框大小!)必须声明高度(请参见可变高度)建议设置溢出:自动防止内容溢出(请参阅溢出)

来源:CSS中的绝对水平和垂直居中

实现这一点有多种方法。

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

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

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

如果有人只关心Internet Explorer 10(及更高版本),请使用Flexbox:

.父级{宽度:500px;高度:500px;背景:黄色;显示:-webkit flex;显示:-ms flexbox;显示:柔性;-webkit调整内容:中心;-ms柔性包装:中心;对齐内容:中心;-webkit对齐项目:中心;-ms flex align:中心;对齐项目:居中;}.居中{宽度:100px;高度:100px;背景:蓝色;}<div class=“parent”><div class=“center”></div></div>

Flexbox支架:http://caniuse.com/flexbox

CSS网格

正文,html{margin:0;}正文{显示:栅格;最小高度:100vh;对齐项目:居中;}<div>div垂直对齐</div>