内联块元素方法display: inline-block
.parent
.child
.parent
width: 100px
height: 100px
border: 1px solid red
text-align: center // 水平居中
font-size: 0
&::after
content: ''
display: inline-block
vertical-align: middle
width: 0
height: 100%
.child
display: inline-block
vertical-align: middle
width: 50px
height: 50px
border: 1px solid blue
!> 可能会在水平方向会有一定的偏移量,《css世界》里面提到‘幽灵节点’,给父容器加了一个font-size:0 解决
表格元素方法dispaly: table-cell
.parent
.child
.parent
width: 100px
height: 100px
border: 1px solid red
font-size: 0
display: table-cell
vertical-align: middle
.child
width: 50px
height: 50px
border: 1px solid blue
margin: 0 auto
相对定位position: absolute
.parent
.child
.parent
width: 100px
height: 100px
border: 1px solid red
position: relative
.child
width: 50px
height: 50px
border: 1px solid blue
position: absolute
top: 0
bottom: 0
left: 0
right: 0
margin: auto
相对定位position + transform
.parent
.child
.parent
width: 100px
height: 100px
border: 1px solid red
position: relative
.child
width: 50px
height: 50px
border: 1px solid blue
position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)
flex布局
.parent
.child
.parent
width: 100px
height: 100px
border: 1px solid red
display: flex
justify-content: center
align-items: center
.child
width: 50px
height: 50px
border: 1px solid blue