CSS居中小技巧
# 内容居中
# 1、文字/内容居中
text-align: center
# 2、文字垂直居中
line-height: height/* line-height高度等于盒子高度 */
# 盒子居中
# 1、盒子水平居中
margin: 0 auto;/*条件盒子是块级元素*/
# 2、flex方法居中
<div class="parent"><div class="child"></div></div>
/* 父盒子 */
.parent {
width: 600px;
height: 600px;
background-color: red;
display: flex; /* 弹性盒子 */
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
}
/* 子盒子 */
.child {
width: 200px;
height: 200px;
background-color: blue;
}
# 3、定位居中(子绝父相)
/* 父盒子 */
.parent {
width: 600px;
height: 600px;
background-color: red;
position: relative;
}
/* 子盒子 */
.child {
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
# 4、table-cell方法居中
/* 父盒子 */
.parent {
width: 600px;
height: 600px;
background-color: red;
display: table-cell; /*以列来排布*/
vertical-align: middle
}
/* 子盒子 */
.child {
width: 200px;
height: 200px;
background-color: blue;
margin: 0 auto;
}
tips:当图片进行机械对齐时有空隙,可以通过
vertical-align: middle
来居中对齐避免空隙问题。