1.为什么要水平垂直居中
在日常开发过程中,我们往往在展示导航栏,列表项等需求时,往往涉及到最多的就是元素水平垂直居中,那么在开发中我们到底怎么样才能水平追至居中呢?下面这几种方法是比较常用和常见的。
2.flex的水平垂直居中
我们可以给父盒子中使用flex布局,并且使用flex中的水平方向和竖直方向进行center,来保证我们的元素是水平垂直居中的
.fatherBox1 {
margin: 8px;
width: 360px;
height: 360px;
display: flex;
align-items: center;
justify-content: center;
background-color: red;
}
.childrenBox1 {
background-color: blue;
}
3.相对绝对布局
我们可以给父盒子相对定位,子盒子绝对定位,并且使用transform来辅佐进行布局,完成水平垂直居中的方案。
.fatherBox2 {
margin: 8px;
width: 360px;
height: 360px;
position: relative;
background-color: red;
}
.childrenBox2 {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: blue;
}
4.相对绝对布局的另一种方案
.fatherBox4 {
position: relative;
;
margin: 8px;
width: 360px;
height: 360px;
background-color: red;
}
.childrenBox4 {
position: absolute;
width: 36px;
height: 36px;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: blue;
}
5.伪元素
伪元素这种会有局限性,只限制子盒子为块级元素。
.box {
width: 200px;
height: 200px;
border: 1px solid;
text-align: center;
}
.box::before {
content: "";
line-height: 200px;
}
.child {
display: inline-block;
background: red;
}
6.flex+margin
下面这种方式会在另一篇文章中详细说明,为什么子盒子使用margin auto就可以完成水平垂直居中了。
.fatherBox3 {
display: flex;
margin: 8px;
width: 360px;
height: 360px;
background-color: red;
}
.childrenBox3 {
width: 36px;
height: 36px;
margin: auto;
background-color: blue;
}
7.总结
其实上面这些用法我们在开发中用的最多的就是flex布局和相对绝对定位这两种方法。