1.margin设置为auto的作用
auto
表示自动填充剩余空间。多用于实现元素居中。
代码和展示效果如下:
<div class="parent">
<div class="child"></div>
</div>
.parent {
background-color: #222;
height: 200px;
width: 200px;
}
.child {
background-color: red;
height: 100px;
width: 100px;
margin: auto;
}
我们知道margin是复合属性,如果单独设置margin-left:auto
,子元素就会靠右展示,因为左边占用了所有剩余空间。
效果如下:
但为什么在上面的例子中设置margin:auto
却只有水平居中,而没有垂直居中呢?
我们知道,块状元素即使设置了宽度,也会沾满一行,因为默认的宽度规则是“适应于父级”规则(在水平方向上自动扩充)。
而auto
的作用是自动填充剩余空间。所以当给块状元素设置margin:auto
时,在水平方向margin
会填充元素中除了border、width、padding
剩余的空间,如果设置为auto
,会平分剩余空间,从而实现水平居中。
但在垂直方向上,块状元素不会自动扩充,它的外部尺寸没有自动充满父元素,也没有剩余空间可说。所以margin:auto
不能实现垂直居中。
2.通过margin实现垂直居中
但如果非要通过margin:auto
实现垂直居中呢,也是可以的。
2.1 子元素设置为absolute或者fixed
当把元素的position
属性值设置为absolute
或fixed
。并且对立方位的属性值一致即可实现水平居中(left/right
)或者垂直(top/bottom
)居中。
.parent{
background-color: #222;
height: 200px;
width: 200px;
position: relative;
}
.absolute-child {
background-color: blue;
position: absolute;
top: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
}
2.2 父元素设置为flex
我们知道通过flex
来实现子元素居中比较方便,根据主轴方向只要设置align-items
或者justify-content
设置为center
即可。但为什么还有通过margin
来设置呢?
我们来通过flex
来实现垂直居中,如下:
<div class="flex-parent">
<div style="width: 100%;">
<div>相对定位</div>
<div>绝对定位</div>
<div>position</div>
<div>margin</div>
</div>
</div>
.flex-parent {
margin-top:10px;
height: 140px;
width: 200px;
background-color: #222;
display: flex;
color: blue;
flex-direction: column;
justify-content: center;
overflow-y: auto;
}
效果还不错!但如果居中的内容数量是不固定的,有可能4个,也有可能是8,10个呢,我们现在把内容增加到8个试试。
可以看到界面出现了滚动条,毕竟我们设置的高度是140px
。但第一个元素就看不到,就算滑动滚动条也看不到。像这样情况我们怎么解决呢?
这个时候就要借助于margin:auto
来实现了。
修改父元素的属性,去除flex-direction
和justify-content
.flex-parent {
margin-top:10px;
height: 140px;
width: 200px;
background-color: #222;
display: flex;
color: blue;
overflow-y: auto;
}
在子元素加上margin:auto
<div class="flex-parent">
<div style="width: 100%;margin:auto">
<div>相对定位</div>
<div>绝对定位</div>
<div>position</div>
<div>margin</div>
<div>border</div>
<div>left</div>
<div>right</div>
<div>bottom</div>
</div>
这样就可以实现,但元素较少时居中显示,但元素较多时也能展示完全。
3.总结
通过margin:auto
我们可以很容易的实现元素水平居中。但要实现垂直居中,可以把子元素设置为position:absolute
或者position:fixed
.也可以把父布局设置为display:flex
。