元素水平垂直居中的需求是比较常见的,在此总结一下。
一、纯文字实现垂直居中(文字水平居中 + line-height: height)
html结构: <div class="text">文字文字<div>
css样式: .text {text-align: center; height: 20px; line-height: 20px}
也可以用下面的方法,但没必要。
二、其他情况实现垂直居中
html结构: <div class="wrapper"><div class="box">需要垂直居中的元素</div><div>
1)自己最喜欢用的是flex布局方法
/*法一*/
.wrapper {
display: flex;
justify-content: center;
align-items: center;
}
/*法二*/
.wrapper {
display: flex;
/*display: inline-flex;
*display: grid;
*display: inline-grid;
*/
}
.box {
margin: auto;
}
2) display: table-cell方法css样式:
.wrapper {
display: table-cell;
vertical-align: middle;
text-align: center;
}
3) position: absolute
/*不知道容器宽高*/
.wrapper {
position: relative;
}
/*法一*/
.box {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
/*法二*/
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
/*知道容器宽高*/
.wrapper {
position: relative;
width: 100px;
height: 100px;
}
.box {
position: absolute;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}
4. 利用相对定位和 transform属性
.box {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}