1、使用position定位实现垂直居中
<1>知道子元素宽高的情况使用margin负值调整
①使用绝对定位left:50%与margin-left取宽度值一半的复数形式设置水平居中。
②使用绝对定位top:50%与margin-top取高度值一半的复数形式设置垂直居中
/* 父元素相对定位,使子元素相对父元素绝对定位 */
.parent{
position: relative;
width: 600px;
height: 600px;
background-color: skyblue;
}
.child{
position: absolute;
width: 200px;
height: 200px;
background-color: #b1ebab;
left: 50%;
top: 50%;
/*用于目标元素宽高已确定 */
margin-left: -100px;
margin-top: -100px;
}
<2>不知道子元素宽高的情况使用transform属性
.parent{
position: relative;
width: 600px;
height: 600px;
background-color: skyblue;
}
.child{
position: absolute;
width: 200px;
height: 200px;
background-color: #b1ebab;
left: 50%;
top: 50%;
/* 用于目标元素宽高不确定 */
transform: translate(-50%,-50%);
}
<3>设置left、right、bottom、top为0,使用margin: auto;调整间距
.parent {
height: 500px;
position: relative;
background-color: #90d5ff;
}
.child {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
height: 100px;
width: 100px;
background-color: #B1EBAB;
margin: auto;
}
2、 Flex布局 居中
<1>使用flex的justify-content和align-items属性
.parent {
height: 500px;
display: flex;
/*元素垂直居中 */
align-items: center;
/* 元素水平居中 */
justify-content: center;
background-color: #87CEEB;
}
.child {
width: 200px;
height: 200px;
background-color: #B1EBAB;
}
<2>使用margin: auto;调整
.parent {
height: 500px;
display: flex;
background-color: #87CEEB;
}
.child {
width: 200px;
height: 200px;
background-color: #B1EBAB;
margin: auto;
}
3、借助table-cell,display: table-cell; vertical-align: middle;
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 500px;
height: 500px;
background-color: #87CEEB;
}
.child {
display: inline-block;
width: 50%;
height: 50%;
background: orange;
}