CSS中的块元素水平垂直居中
一、使用flex布局,要考虑兼容性问题:
.parent {
display: flex;
justify-content:center;
align-items:center;
}
二、绝对定位 + transform: translate,要考虑兼容性问题:
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
三、绝对定位 + margin: auto,适用于盒子有宽高的情况:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
四、绝对定位 + margin负值,适用于盒子宽高已知的情况:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /* 自身 height 的一半 */
margin-left: -50px; /* 自身 width 的一半 */
}