一、单行文本垂直居中
垂直居中:text-align:center;
水平居中:height = line-height
二、块元素垂直居中
<div className=“parent”>
父元素
<div className=“child”>子元素</div>
</div>
2.1 已知宽高
【position+margin】
使用position+margin减去子元素宽高的一半实现
.parent{
position:relative;
.child{
width:200px;
height:200px;
position:absolute;
top:50%;
left:50%;
margin:-100px 0 0 -100px;
}
}
【table-cell】
.parent{
width:400px;
height:400px;
display:table;
.child{
width:200px;
height:200px;
display:table-cell;
vertical-align:middle;
}
}
【grid布局】
.parent{
display: grid;
height: 400px;
.child{
align-self: center; /*设置单元格内容的垂直位置*/
justify-self: center; /*设置单元格内容的水平位置*/
}
}
2.2 未知宽高
【position+transform】
.parent{
position:relative;
.child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
}
【position+margin:auto 五马分尸】
.parent{
position:relative;
.child{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
}
}
2.3 已知未知宽高皆可
【flex布局】
.parent{
display:flex;
justify-content:center;
align-items:center;
}