我想用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?
当前回答
以下是我的案例,并在Firefox中进行了测试。
#element {
display: block;
transform: translateY(50%);
-moz-transform: translateY(50%);
-webkit-transform: translateY(50%);
-ms-transform: translateY(50%);
}
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;
}
这在我的情况下有效(仅在现代浏览器中测试):
.textthatneedstobecentered {
margin: auto;
top: 0; bottom: 0;
}
只需这样做:在div中添加类:
.modal {
margin: auto;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
height: 240px;
}
请阅读本文以获得解释。注:高度是必需的。
.中心{位置:绝对;顶部: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{宽度:100%;高度:200px;显示:柔性;边框:1px实心#000;}.内部div{边距:自动;文本对齐:居中;边框:1px纯红色;}<div class=“outer div”><div class=“inner div”>嘿!</div></div>