当DIV只有一层时 vertical-align:middle; 是起作用,为什么DIV嵌套基层就不起作用的。
下面这个是有作用的:
<html>
<meta charset="utf8">
<style>
.Absolute-Center {
display: table-cell;
width: 100px;
height: 100px;
border:1px solid red;
text-align:center;
vertical-align:middle;
}
</style>
<body>
<div class="Absolute-Center">
<p>居中</p>
</div>
</body>
</html>
当嵌套几个时就不起作用了。那要如何处理呢。
给.center-inner加上 display: table; 然后给 p 加上 display:table-cell; 即可。
<html>
<meta charset="utf8">
<style>
.outer{
width:300px;
height:500px;
border:1px solid red;
position:relative;
}
.center {
position: absolute;
margin: auto;
top:0px; bottom:0px; left:0px; right:0px;
width: 100px; height: 100px;
border:1px solid red;
}
.center-inner {
display: table;
height: 100%; width: 100%;
}
.center p {
display: table-cell;
text-align:center; vertical-align:middle;
}
</style>
<body>
<div class="outer">
<div class="center">
<div class="center-inner">
<p>居中</p>
</div>
</div>
</div>
</body>
</html>
注释转载:
将对象呈递为内联对象,但是对象的内容作为块对象呈递。旁边的内联对象会被呈递在同一行内!
说的通俗点,就是你设置的当前div属性还是块对象呈递,但是允许同一级别的div在同一行内,也可以设置宽度和高度!
position: absolute; display: table-cell; equals display: block; position: absolute;
And
vertical-align only applies to inline/table-cell elements.