水平居中:
(1)行内元素:text-align:center;
(2)块级元素:margin:auto;
(3)定位元素:left:50%+margin-left:负(自身宽度的一半);
(4)flex布局:justify-content:center;
垂直居中:
(1)行内元素:line-height属性值等于height值。
(2)定位元素:top:50%;+margin-top:负(自身高度的一半);
(3)绝对定位+平移(不需知道元素高度);
.father {
width: 200px;
height: 200px;
background-color: rgb(20, 221, 228);
position: relative;
}
.son {
background-color: rgb(99, 211, 48);
position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0px;
}
<!-- 1.不能确定元素高度 -->
<div class="father">
<p class="son">垂直居中</p>
</div>
(4)绝对定位元素:top,left,right,bottom均设置为0,+margin:auto;(不需要确定元素高度)
.father2 {
width: 200px;
height: 200px;
background-color: rgb(34, 20, 228);
position: relative;
}
.son2 {
background-color: rgb(99, 211, 48);
position: absolute;
height: 30px;
width: 100px;
top: 0;
right: 0;
bottom: 0;
left: 0;
/* !!!margin */
margin: auto;
}
<div class="father2">
<p class="son2">垂直居中</p>
</div>
(5)flex布局(不需要确定元素高度)
.father3 {
width: 200px;
height: 200px;
background-color: rgb(20, 221, 228);
display: flex;
align-items: center;
}
.son3 {
background-color: rgb(99, 211, 48);
}
<div class="father3">
<p class="son3">垂直居中</p>
</div>