1:类似子div加空span的方法用伪类实现
<div class="outer">
<div class="inner">一段文字</div>
</div>
.outer{
height: 200px;
width: 200px;
text-align: center;
background: #43e;
}
.inner{
height: 100px;
background: #de4;
width: 100px;
display:inline-block;
vertical-align: middle;
}
.outer:after{
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
2:通过position: absolute;实现包括两种方法实现
第一种:top/left各50%; margin-left:width/2; margin-top:height/2实现
<div class="outer">
<div class="inner">一段文字</div>
</div>
.outer{
height: 200px;
width: 200px;
position: relative;
background: #43e;
}
.inner{
height: 100px;
background: #de4;
position: absolute;
width: 100px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
display:inline-block;
vertical-align: middle;
}
第二种:子div绝对定位:margin:auto;
<div class="outer">
<div class="inner">一段文字</div>
</div>
.outer{
height: 200px;
width: 200px;
position: relative;
background: #43e;
}
.inner{
height: 100px;
background: #de4;
position: absolute;
width: 100px;
top:0px;
left:0px;
bottom:0px;
right:0px;
margin:auto;
}
3:通过transform属性实现
<div class="outer">
<div class="inner">一段文字</div>
</div>
.outer{
height: 200px;
width: 200px;
position: relative;
background: #43e;
}
.inner{
height: 100px;
background: #de4;
position:absolute;
width: 100px;
top:50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
4:通过弹性盒子:flex实现
<div class="outer">
<div class="inner">一段文字</div>
</div>
.outer{
height: 200px;
width: 200px;
background: #43e;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
height: 100px;
background: #de4;
width: 100px;
}
多为网上总结(有更多方法,请评论分享,谢谢)