在书写css代码时,经常会碰见给元素进行居中(水平居中和垂直居中)的操作,下面我将梳理几种常见的居中操作的代码
1.水平居中
(1)通过margin:auto实现
设置盒子margin : 0 auto:这种居中方式的原理在于设置margin-left为auto时,margin-left就会被设置为能有多大就设置多大,所以盒子会跑到最右边,而设置margin-right为auto时,同理盒子就会跑到最左边。所以,当我们设置左右的margin都是auto 的时候,盒子就跑到了中间,从而形成了水平居中。
<div class="father">
<div class="son">盒子</div>
</div>
<style lang="less" scoped>
.son {
background-color: pink;
width: 100px;
height: 100px;
margin:0 auto;
}
<style>
(2)通过text-align:center
将子元素设置为display:inline-block;父元素使用text-align:center即可实现居中
2.通过vertical-align:middle实现垂直居中
通过vertical-align:middle 实现垂直居中是最常使用的方法,但是有一点需要格外注意, vertical生效的前提是元素的display : inline-block。并且在使用vertical-align:middle 的时候需要一个兄弟元素做参照物,让它垂直于兄弟元素的中心点。vertical-align对齐的方法是寻找兄弟元素中最高的元素作为参考。
<div class="father">
<div class="son">盒子</div>
</div>
<style lang="less" scoped>
.father {
width: 100%;
height: 500px;
text-align: center;
background-color: #999;
// 添加伪元素作为参照物
&:before {
content: " ";
height: 100%;
display: inline-block;
vertical-align: middle;
}
.son {
display: inline-block;
background-color: pink;
width: 100px;
height: 100px;
vertical-align: middle;
}
}
</style>
3.给父元素添加flex布局(水平+垂直居中)
给父元素添加flex弹性布局,然后使用justify-content:center, align-items:center使其中的子元素排列在父元素的最中间实现居中效果
<div class="father">
<div class="son">盒子</div>
</div>
<style lang="less" scoped>
.father {
width:100%;
height:600px;
background-color:#999
display: flex
justify-content: center;
align-items:center;
.son {
background-color: pink;
width: 100px;
height: 100px;
}
}
<style>
4.使用相对定位实现居中效果
这种方法使用了子绝父相的做法,子元素设置绝对定位,父元素设置相对定位。通过控制子元素的margin值来使子元素刚好位于父元素最中间
<div class="father">
<div class="son">盒子</div>
</div>
<style lang="less" scoped>
.father {
position: relative;
width: 100%;
height: 500px;
background-color: #999;
.son {
position: absolute;
background-color: pink;
left: 50%;
margin-left: -50px;
// left:calc(50% - 50px)
top: 50%;
margin-top: -50px;
// top:calc(50% - 50px)
width: 100px;
height: 100px;
}
}