垂直居中几种常见的实现方式总结
1.使用flex实现 垂直居中。
①、使用flex的justify-content和align-items属性
.parent {
height: 500px;
background-color: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
.son{
width: 100px;
height: 100px;
background-color: red;
}
②、flex使用margin平分间距
.parent{
height: 500px;
display: flex;
background-color: #0000FF;
}
.son{
height: 100px;
width: 100px;
background-color: red;
margin: auto;
}
2.使用position定位实现垂直居中。
①设置left、right、bottom、top为0,使用margin调整间距
.parent{
height: 500px;
position: relative;
background-color: #0000FF;
}
.son{
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
height: 100px;
width: 100px;
background-color: red;
margin: auto;
}
②知道子元素宽高的情况使用margin负值调整。
.parent{
height: 300px;
position: relative;
background-color: #0000FF;
}
.son{
position: absolute;
left: 50%;
top: 50%;
height: 100px;
width: 100px;
background-color: red;
margin-left: -50px;
margin-top: -50px;
}
③不知道子元素宽高的情况使用transform属性。
.parent{
height: 300px;
position: relative;
background-color: #0000FF;
}
.son{
position: absolute;
left: 50%;
top: 50%;
background-color: red;
transform: translate(-50%, -50%);
}
还有一种方式是使用display=table和table-cell实现,这种方式没有兼容问题,上面的flex和transform都存在兼容性问题。