版权声明:原创的文章转载请注明出处,谢谢! https://blog.csdn.net/weixin_41804429/article/details/82631317
元素水平垂直居中的需求是比较常见的,在此总结一下。
一、纯文字实现垂直居中(文字水平居中 + line-height: height)
html结构: <div class="text">文字文字<div>
css样式: .text {text-align: center; height: 20px; line-height: 20px}
也可以用下面的方法,但个人觉得用line-height是最佳的。
二、其他情况实现垂直居中
有很多种方法,在此只列3种。
html结构: <div class="wrapper"><div class="box">需要垂直居中的元素</div><div>
1)自己最喜欢用的是flex布局方法
css样式: .wrapper {display: flex; justify-content: center; align-items: center;}
2) display: table方法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;
}
//知道容器宽高
.wrapper {
position: relative;
width: 100px;
height: 100px;
}
.box {
position: absolute;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}