项目里经常在元素排列时会需要垂直居中的情况,以下在使用场景和条件限制上总结部分常用的一些垂直居中方法。
1.单行垂直居中
将元素的height
和line-height
设定为相同的值即可;
2.table-cell Demo
利用display:table-cell
赋予div类似于table
等标签的表格布局特性,
.middle{
text-align: center;
display: table-cell;
//以单元格方式进行解析
//此时避免使用float和position等其他属性以免冲突影响
vertical-align: middle;
//垂直居中
}
此方法兼容所有浏览器
关于table的更多使用可以参考
css Table布局-display:table
display:table-cell实现水平垂直居中
3.绝对定位+0 Demo
需要确定内部元素的高度才能生效:
.middle-wrapper{
position:relative;
}
.middle{
height: 40px;
position: absolute;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
此方法兼容所有浏览器
4.绝对定位+负边距实现居中 Demo
.list li .btn{
display: inline-block;
cursor: pointer;
border:1px solid #3a8eff;
border-radius: 5px;
color: #3a8eff;
height: 40px;
line-height: 40px;
position: absolute;
top: 50%;
width: 100%;
left: 0;
margin-top: -20px; /*子元素需要设定高度*/
/*transform:translateY(-50%);*/
}
类似的负边距结合transform
也可以实现垂直居中,此时子元素不需要设定高度也可以,但是不能兼容ie678。
5.通过:after来占位 Demo
.box{
text-align:center;
font-size:0;
}
.box span{
font-size:16px;
}
.box:after{
content:'';
width:0;
height:100%;
display:inline-block;
vertical-align:middle;
}
6.flex弹性布局居中
- 在父元素上设置相关属性即可使子元素居中:
.wrap{
display:flex; /*使用flex盒子*/
justify-content:center;/*水平轴上居中*/
align-items:center;/*垂直轴上居中*/
}
- 父元素设置为弹性容器display:flex,子元素设置magrin:auto :
.wrap{
display:flex;
}
.child{
margin: auto;
}