一个html中只有一个div。
<div class="test">
</div>
css1:
.test{
width:200px;
height:200px;
border:1px solid red;
margin:0 auto;
}
css1可以使div.test左右居中。
css2:
.test{
width:200px;
height:200px;
border:1px solid red;
margin:auto auto;
}
为何css2不可以使div.test上下左右居中??
请不要回答如何使他div.test上下左右居中,请回答为何margin:auto auto;不能上下左右居中??
The following constraints must hold among the used values of the other properties:
'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
下面是关于高度的:
If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0. If 'height' is 'auto', the height depends on whether the element has any block-level children and whether it has padding or borders:
因为规范就是这么规定的算法,浏览器就是这么实现的。
CSS规范