1、水平居中
(1)
.box {
width: 200px;
height: 200px;
margin: 0 auto;
background-color: aqua;
}
(2)
.box {
position: absolute;
left:50%;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: aqua;
}
(3)
.box {
position: absolute;
left:50%;
transform: -50%;
width: 200px;
height: 200px;
background-color: aqua;
}
(4)下面是写到父元素上,子元素居中,使用flex布局
.box {
display: flex;
justify-content: center;
width: 200px;
height: 200px;
background-color: aqua;
}
.son {
width: 80px;
height: 80px;
background-color: blue;
}
2、垂直居中
(1)
.son {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0 ;
width: 80px;
height: 80px;
background-color: blue;
}
(2)子元素被居中
.box {
position: relative;
width: 200px;
height: 200px;
background-color: aqua;
display:table-cell;
vertical-align: middle;
}
.son {
width: 80px;
height: 80px;
background-color: rgb(167, 167, 194);
}
(3)
.box {
position: absolute;
top: 50%;
margin-top: -100px;
width: 200px;
height: 200px;
background-color: chartreuse;
}
(4)使用flex布局,父元素开启flex布局,子元素设置垂直居中
.box {
display: flex;
width: 200px;
height: 200px;
background-color: aqua;
}
.son {
align-self: center;
width: 80px;
height: 80px;
background-color: blue;
}
(5)
.box {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 200px;
height: 200px;
background-color: chartreuse;
}
文本居中
水平居中 :text-algin:center
;
垂直居中: line-hight:xxpx
;(xx为父元素盒子的高度)