我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。
<body>
<div>Div to be aligned vertically</div>
</body>
如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?
我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。
<body>
<div>Div to be aligned vertically</div>
</body>
如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?
当前回答
我觉得这个最有用。。。它给出了最准确的“H”布局,并且非常容易理解。
这种标记的好处是您可以在一个地方定义内容大小->“PageContent”。
页面背景的颜色及其水平边距在其相应的div中定义。
<div id="PageLayoutConfiguration"
style="display: table;
position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
width: 100%; height: 100%;">
<div id="PageBackground"
style="display: table-cell; vertical-align: middle;
background-color: purple;">
<div id="PageHorizontalMargins"
style="width: 100%;
background-color: seashell;">
<div id="PageContent"
style="width: 1200px; height: 620px; margin: 0 auto;
background-color: grey;">
My content goes here...
</div>
</div>
</div>
</div>
这里用CSS分隔:
<div id="PageLayoutConfiguration">
<div id="PageBackground">
<div id="PageHorizontalMargins">
<div id="PageContent">
my content goes here...
</div>
</div>
</div>
</div>
#PageLayoutConfiguration{
display: table;
width: 100%;
height: 100%;
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#PageBackground{
display: table-cell;
vertical-align: middle;
background-color: purple;
}
#PageHorizontalMargins{
width: 100%;
background-color: seashell;
}
#PageContent{
width: 1200px;
height: 620px;
margin: 0 auto;
background-color: grey;
}
其他回答
实现这一点有多种方法。
使用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>
实际上,垂直居中需要两个div。包含内容的div必须具有宽度和高度。
#集装箱{位置:绝对;顶部:50%;页边空白:-200像素;/*#内容高度的一半*/左:0;宽度:100%;}#内容{宽度:624px;左边距:自动;右边距:自动;高度:395px;边框:1px实心#000000;}<div id=“container”><div id=“content”><h1>居中的div</h1></div></div>
这是结果。
不幸的是,但并不令人惊讶的是,解决方案比人们希望的更复杂。同样不幸的是你需要在垂直居中的div周围使用额外的div。
对于符合标准的浏览器,如Mozilla、Opera、Safari等,您需要将外部div设置为显示为表,将内部div设置为表单元格-然后可以垂直居中。对于InternetExplorer,您需要将内部div绝对放置在外部div中,然后将顶部指定为50%。以下页面很好地解释了这一技术,并提供了一些代码示例:
CSS中的垂直居中未知高度的CSS垂直居中(兼容Internet Explorer 7)(Wayback Machine提供的存档文章)
还有一种使用JavaScript进行垂直居中的技术。内容与JavaScript和CSS的垂直对齐演示了这一点。
我只是找到了另一种对我有用的方法:
<div class="container">
<div class="vertical">
<h1>Welcome</h1>
<h2>Aligned Vertically</h2>
<a href="#">Click ME</a>
</div>
</div>
CSS
.vertical{
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
更多信息
这在我的情况下有效(仅在现代浏览器中测试):
.textthatneedstobecentered {
margin: auto;
top: 0; bottom: 0;
}