最近复习html和css的内容,想起来一个之前没想明白的问题,为什么块级元素margin:0 auto可以实现水平居中,而margin:auto不能实现水平垂直双居中呢?
margin:0 auto居中的原理
#parent{
height: 200px;
width: 200px;
background: black;
margin: 0 auto;
}
#child{
height: 100px;
width: 100px;
background: red;
margin: 0 auto;
}
块级元素设置居中的前提是设置了width,若在css中没写width则会默认占据100%的宽度。auto指平分剩余空间 比如上图中我父div宽度为200px,子div宽度为100px,则水平方向平分剩余宽度为(200-100)/2
我们知道margin:0 auto和margin:0 auto 0 auto是相同的,当只有一条边被设置了auto时
#parent{
height: 200px;
width: 200px;
background: black;
margin: 0 auto;
}
#child{
height: 100px;
width: 100px;
background: red;
margin: 0 auto 0 0;
}
我们发现子div被移动到了一侧,上图子divmargin:0 auto 0 0,只给了右边设置了auto相当于让右边自己平分剩余空间,即把父div的剩余空间全都给了右侧;
怎么实现垂直方向居中
为什么margin:auto不能实现在垂直方向上的居中呢?
因为默认垂直方向上没有剩余空间
如果子元素设置了绝对定位且四边都设为0,子元素会填充整个父元素的所有剩余空间,auto就能平均分配水平和垂直方向的剩余空间了。
#parent{
height: 200px;
width: 200px;
background: black;
margin: 0 auto;
}
#child{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 100px;
width: 100px;
background: red;
margin: auto ;
}