记录两个思路,当然还有其他方法,如果用到再补充:
<div class="parent" style="background:red;width:200px;height:100px;">
<div class="child" style="background:lightblue;">测试文字</div></div>
1.在伸缩容器上使用主轴对齐justify-content和侧轴对齐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实现单行文本水平垂直居中
.test{text-align: center;line-height: 100px;