HTML
<div id="centered">
//Some Content
</div>
CSS
#centered
{
margin-left:auto;
margin-right:auto;
}
无论屏幕大小如何,上面的代码都是水平对齐的。 如何在中心垂直对齐相同的div?
答案 0 :(得分:0)
如果您知道div的宽度和高度
然后(我假设它是400 X 200),所以在margin属性中给这些维度的一半值赋予负数。你的内容将集中在中
#centered{
position:absolute;
top:50%;
left:50%;
margin-left:-200px;
margin-top:-100px;
}
如果您的宽度和高度是动态的,然后put this div in table
,以便您可以垂直和水平对齐此中间
答案 1 :(得分:0)
尝试以下css:
#centered
{
position: absolute;
height: auto;
width: auto;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
答案 2 :(得分:0)
试试这段代码..
#centered
{
margin-left:auto;
margin-right:auto;
display: table-cell; // here is the trick
vertical-align:middle; // and this
height:200px;
border:1px solid blue;
}