HTML结构
注:该HTML为React写法,也可使用原生HTML代替。
<div className={styles.parent}>
<div className={styles.children}>子盒子</div>
</div>
(1)绝对定位盒子居中
.parent {
position: relative;
}
.children {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
(2)flex盒子居中
.parent {
display: flex;
justify-content: center;
align-items: center;
}
(3)grid盒子居中(含兼容性问题)
.parent {
display: grid;
align-items: center;
justify-content: center;
}
(4)table-cell文字居中
.children {
display:table-cell;
vertical-align:middle;
text-align: center;
}
(5)margin盒子水平居中
.children {
margin: 0 auto;
}
(6)文字水平居中
.children {
text-align: center;
}
(7)文字垂直居中(height与line-height等高)
.children {
height: 200px;
line-height: 200px;
}
(8)table-cell盒子垂直居中
.parent {
display: table-cell;
vertical-align: middle;
}