设置父元素position为relative,要居中的子元素position为absolute,然后设置居中子元素的位置的top和left均为50%,再将该元素进行平移translate(-50%,-50%)
<div class="myParent">
<span class="myChild">123</span>
</div>
效果:
css:
.myParent{
background: red;
height: 80px;
width: 300px;
position: relative;
.myChild{
color: #fff;
background: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
}