不管水平居中仍是垂直居中相信你並不陌生,但有多少種實現方式,每種的優劣以及兼容性相信你並不清楚。bash
.par{text-align:center;}
.sub{margin:0 auto;}
.sub{margin-left: auto;margin-right:auto;}
複製代碼
單行文本垂直居中,行高等於高度flex
.par{
height:40px;
line-height:40px}
複製代碼
單行文本和圖片垂直居中,行高等於高度,而且設置對齊方式爲middle,前提圖片的高度在行高以內spa
.par{ height:40px;line-height:40px;}
.par .sub{vertical-align:middle;}
複製代碼
容器高度不肯定,多行文本垂直居中,內容總體高度不肯定,padding-top=padding-bottom,code
容器高度肯定,多行文本垂直居中,內容總體高度不肯定orm
//方案一
.par{display:table;}
.par .sub{
display:table-cell;
vertical-align:middle;}
//方案二
.par .sub{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%)}
//方案三,缺一不可,必須保證三行代碼
.par {
display:flex;
flex-direction:column;
justify-content:center;}
複製代碼
容器高度肯定,內容總體高度肯定圖片
//方案一
.par{
height:200px;
}
.par:before{
height: 50%;
content: "";
width: 100%;
display: block;
}
.par .sub{
height:50px;
margin-top:-25px;
}
//方案二
.par{
height:200px;
}
.par .sub{
height:50px;
position:absolute;
left:50%;
top:50%;
margin-top:-25px;
}
//方案三,缺一不可
.par {
display:flex;
flex-direction:column;
justify-content:center;}
複製代碼