描述
一个块级元素设置width的情况下,添加margin:0 auto
可以实现该元素在父级元素中水平居中
分析
如果要实现居中效果,宽度是一定要设置的,auto是指平分剩余空间
.father {
width: 600px;
height: 200px;
background: #ccc
}
.son {
width: 200px;
height: 200px;
margin: 0 auto
}
如果只设置了一侧的auto
.son {
width: 200px;
height: 200px;
margin-left: auto
}
- 结果子盒子在另一侧对齐
这是因为左侧设置了auto,父元素的剩余空间都分配给了左侧,右侧就没有边距了
所以理论上讲可以实现垂直方向上的居中,但是垂直方向不能直接使用auto,因为垂直方向默认是由内容撑开的,没有剩余空间了
.son {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
width: 50px;
height: 50px;
margin: auto;
background-color: pink;
}
给子盒子设置绝对定位,占满父盒子,使用auto平分剩余空间,能够实现水平和垂直居中
总结
想要实现水平垂直居中的方式有三种:
- 使用flex布局:
justify-content: center;align-items: center;
-
使用绝对定位+位移:向右向下移动父盒子的50%,再向左向上移动自身的50%
-
使用本文提到的
margin:auto
文章评论