作为css的初学者,我们经常利用margin属性来实现盒子的居中效果;
使用margin:auto,却发现盒子只在水平方向实现了居中效果
<style>
/* 探究auto是怎么计算的 */
*{
margin: 0;
padding: 0;
}
.outer{
height: 500px;
width: 500px;
background-color: aqua;
/* display: flex; */
}
.inner{
height: 100px;
width:50px;
margin: auto;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
如果在不考虑垂直方向,设margin: 0 20px 0 auto
发现只有设了实际参数的右外边距起作用,左外边距是外盒子所剩下的内容区
我认为在水平方向上,如果没有设定实际参数,都是auto的情况下,两个auto会默认平等分掉剩下的外盒子内容区,如果设有一个auto,则这个auto获得剩下的内容区作为外边距
总结:在水平方向上auto是根据所剩的内容区所计算外边距
但如果将盒子设为display:flex;内盒子就能实现上下居中,是因为在我们的习惯中,我们滑动页面都是往垂直方向滑动,水平方向在pc网页设置滚轮就十分不方便,所以水平方向是有自适应属性,而在垂直方向上,有滚轮的设计,没有自适应属性,而弹性盒给予了外盒自适应属性,从而aumargin:auto能使在垂直方向上居中