記錄兩個思路啤斗,當(dāng)然還有其他方法赁咙,如果用到再補(bǔ)充:
<div class="parent" ?style="background:red;width:200px;height:100px;">
<div class="child" style="background:lightblue;">測試文字</div></div>
1.在伸縮容器上使用主軸對齊justify-content和側(cè)軸對齊align-items
.parent{
display: flex;
justify-content: center;?
align-items: center;}
2.使用position:absolute;
(1)不考慮子元素和父元素的寬高
.parent{
position:relative;
}
.child{
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}
(2)子元素寬高固定
.parent{
position: relative;}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 80px;
height: 60px;
margin-left: -40px;
margin-top: -30px;}
3.
text-align + line-height實現(xiàn)單行文本水平垂直居中
.test{
text-align: center;
line-height: 100px;}