CSS3提供了很多方法来让子元素居中, 下面介绍一些常用的方式:
/*1. 块级元素*/
.parent {
display: flex;
justify-content: center;
align-items: center;
}
/*2. 行内元素*/
.parent {
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
}
/*3. 绝对定位*/
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/*4. 伸缩布局*/
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
/*5. 表格布局*/
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}