我想用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:
1) 位置:相对;
2) 顶部:50%;
3) 变换:translateY(-50%);
以下是一个示例:
外部配电盘{高度:170px;宽度:300px;背景色:浅灰色;}中间分隔符{位置:相对;顶部:50%;-webkit转换:translateY(-50%);-ms变换:translateY(-50%);变换:translateY(-50%);}<div class='outer-div'><div class='middle-div'>测试文本</div></div>
.中心{位置:绝对;顶部:50%;左:50%;转换:转换(-50%,-50%);/*(x,y)=>位置*/-ms转换:转换(-50%,-50%);/*即9*/-webkit转换:转换(-50%,-50%);/*Chrome、Safari、Opera*/}.垂直{位置:绝对;顶部:50%;//左:0;变换:平移(0,-50%);/*(x,y)=>位置*/}.水平{位置:绝对;//顶部:0;左:50%;变换:平移(-50%,0);/*(x,y)=>位置*/}第二部分{填充:1em;背景色:灰色;颜色:白色;} <body><div class=“vertical”>垂直向左</div><div class=“horizontal”>水平顶部</div><div class=“center”>垂直水平</div></body>
相关:居中图像
不幸的是,但并不令人惊讶的是,解决方案比人们希望的更复杂。同样不幸的是你需要在垂直居中的div周围使用额外的div。
对于符合标准的浏览器,如Mozilla、Opera、Safari等,您需要将外部div设置为显示为表,将内部div设置为表单元格-然后可以垂直居中。对于InternetExplorer,您需要将内部div绝对放置在外部div中,然后将顶部指定为50%。以下页面很好地解释了这一技术,并提供了一些代码示例:
CSS中的垂直居中未知高度的CSS垂直居中(兼容Internet Explorer 7)(Wayback Machine提供的存档文章)
还有一种使用JavaScript进行垂直居中的技术。内容与JavaScript和CSS的垂直对齐演示了这一点。
这在我的情况下有效(仅在现代浏览器中测试):
.textthatneedstobecentered {
margin: auto;
top: 0; bottom: 0;
}
经过大量研究,我终于找到了最终的解决方案。它甚至适用于浮动元素。查看源
.element {
position: relative;
top: 50%;
transform: translateY(-50%); /* or try 50% */
}