search

Home  >  Q&A  >  body text

javascript - Why can't margin:auto auto be aligned up, down, left, and right?

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梦2745 days ago1183

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-06-24 09:44:38

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

    reply
    0
  • 阿神

    阿神2017-06-24 09:44:38

    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?

    reply
    0
  • 某草草

    某草草2017-06-24 09:44:38

    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!

    reply
    0
  • PHP中文网

    PHP中文网2017-06-24 09:44:38

    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

    reply
    0
  • Cancelreply