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 解決
css
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%)
.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