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

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

如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置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中的绝对水平和垂直居中

其他回答

特别是对于具有相对(未知)高度的父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>

要垂直对齐网页(包括Internet Explorer 6)中的框,可以使用:

有条件的评论haslayout属性显示:其他表值(现在为flex)

不停摆弄

/*Internet Explorer 8和其他*/.主要{宽度:500px;边距:自动;边框:实心;}html格式{高度:100%;宽度:100%;显示:表格;}正文{显示:表格单元格;垂直对齐:中间;}<!-- [如果lte IE 7]><style>/*应该在<head>中*/html,正文,.ie{高度:100%;文本对齐:居中;空白:nowrap;}例如,.main{显示:内联;/*在使用块元素而不是内联元素时与缩放一起使用*/缩放:1;垂直对齐:中间;文本对齐:左侧;空白:正常;}</style><b class=“ie”></b><!--[endif]--><div class=“main”><p>用你的内容填满它</p><p><a href=“https://jsfiddle.net/h8z24s5v/embedded/result/“>JsFiddle版本</a></p></div>

实际上,InternetExplorer7在这里会带来一些麻烦,因为它是唯一严格应用高度的浏览器:100%应用于HTML/body元素。


但是,这是过去和现在的事了,谁还记得旧版本的Internet Explorer,表/表单元格很好,display:flex很有前途,display:grid总有一天会出现。


现在通过flex的另一个示例

html格式{显示:柔性;最小高度:100vh;/*或高度*/}正文{边距:自动;}<div>div垂直对齐</div>

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

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

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

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

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

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