Why don't margin-top: auto and margin-bottom:auto work the same as their left and right counterparts?

后端 未结 2 944
名媛妹妹
名媛妹妹 2020-11-30 10:19

If I set the CSS margin properties of a div like so:

div { margin-left: auto; margin-right: auto; }

I get a div which is centered horizonta

相关标签:
2条回答
  • 2020-11-30 10:24

    The short answer is the spec says so.

    10.6.2 Inline replaced elements, block-level replaced elements in normal flow, 'inline-block' replaced elements in normal flow and floating replaced elements

    If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0.

    http://www.w3.org/TR/CSS2/visudet.html#Computing_heights_and_margins

    0 讨论(0)
  • 2020-11-30 10:40

    Assuming we are talking about auto margins within a Flexbox..

    The reason that margin-left and margin-right set to auto will center an item is because the width by default is 100% of the available container for a block element.

    The height on the other hand attempts to fill as little as the space as possible, so margin-top and margin-bottom as auto will default to 0. BUT, if your element is within an element with a fixed height, then margin-top and margin-bottom will be able to calculate the center based on that height.

    Ex. http://jsfiddle.net/jwz76e3g/24/

    0 讨论(0)
提交回复
热议问题