场景1,已设定父元素高度,子元素是行内元素,则实现是由其内容高度(line-height)撑开的
<div class="father">
<span class="child">no</span>
</div>
.father{
height: 200px;
200px;
line-height: 200px; /*垂直居中*/
text-align: center; /*水平居中*/
}
.child{
background: gray;
}
场景2,子元素是块级元素且没有设定高度(未知子元素高度)
<div class="father">
<div class="child">no</div>
</div>
.father{
height: 200px;
200px;
display: table-cell;
vertical-align: middle; /*垂直居中*/
text-align: center; /*水平居中*/
}
.child{
background: gray;
display: inline-block;
}
场景3,子元素是块级元素,已设定高度(已知子元素高度)
.father{
height: 200px;
200px;
position: relative;
}
.child{
height: 100px;
100px;
position: absolute; /*垂直居中* 也可采用margin方法(father-child/2)*/
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: gray;
}
(还可采用flex方法)