水平居中
内联元素
text-align: center
这个属性会让内联子元素水平居中
块级元素
margin-left: auto;
margin-right: auto;
水平居中通用方法
margin-left: 50%;
transform: translateX(-50%);
这个方法可以让内联元素自身居中,margin的百分值是相对于父元素的,相当于position: relative; left: 50%
,transformX的百分值是针对自身的,相当于margin-left:-自身大小一半
,但它原来的位置空间还是在的
定位居中
position: absolute;
letf: 50%;
transform: translateX(-50%);
垂直居中
内联元素
.parent {
height: 100px;
}
.children {
line-height: 100px; /* 将行高设置为和父元素一样高就可以了*/
}
定位居中
position: absolute;
top: 50%;
transform: translateY(-50%);
flex布局
.parent {
display: flex;
align-items: center; /* 水平居中 */
justify-content: center; / * 垂直居中 */
margin: auto; /* 水平垂直居中 */
}
.children {
/* */
}