CSS水平垂直居中方案【前端面试必备!!】
1、单行文本
div {
height:100px;
line-height: 100px;
text-align: center;
}
2、定高(position + margin) —— 前提是父级要有高度
div {
position: absolute;
height: 100px;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
3、不定高(position+transform) —— 前提是父级要有高度
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4、不定高(flex)—— 推荐
div {
display: flex;
align-item: center;
justify-content: center;
}
5、不定高(table)
.parent{
display: table-cell;
text-align: center;
.child {
vertical-align: middle;
}
}