javascript - Why can't margin:auto auto be aligned up, down, left, and right?
过去多啦不再A梦
过去多啦不再A梦 2017-06-24 09:42:38
0
4
1185

There is only one p in an html.

<p class="test">
</p>

css1:

.test{
    width:200px;
    height:200px;
    border:1px solid red;
    margin:0 auto;
    }

css1 can center p.test left and right.

css2:

.test{
    width:200px;
    height:200px;
    border:1px solid red;
    margin:auto auto;
    } 

为何css2不可以使p.test上下左右居中?? 
请不要回答如何使他p.test上下左右居中,请回答为何margin:auto auto;不能上下左右居中?? 
过去多啦不再A梦
过去多啦不再A梦

reply all(4)
大家讲道理

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规范

阿神

This is a good question. Let me ask you, when there are two elements in a row, can you center them left and right? In the same way, when there may be elements above and below you, how do you want the browser to calculate the position where the corresponding element should exist?

某草草

No, if you don’t use flex layout for top and bottom alignment, there is no good way. Virtical–align is not easy to use either!

洪涛

No, if you want to center the top, bottom, left, and right, it is recommended to use flex layout, followed by table, table-cell or positioning

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template