What is the rationale behind margin-top: auto and margin-bottom: auto amounting to 0 margin?

前端 未结 1 1966
广开言路
广开言路 2021-01-15 00:21

Since margin-right: auto and margin-left: auto center an element horizontally, I would expect their vertical counterparts to behave in the same way

1条回答
  •  失恋的感觉
    2021-01-15 01:01

    As noted above:

    Aha... That's not so obscure! I can see it being useful. Thanks for the example you gave on jsfiddle.

    So, if an element is absolutely positioned in relation to the parent element, using both top and bottom, yet it's height is defined and is less then the height of the parent element minus the top and bottom offsets, then the margin property will be used to determine it's vertical alignment in relation to the parent, and margin:auto will result in a vertically centered element.

    True, it sounds complicated, yet it's clear on jsfiddle.

    For example, this CSS:

    .inner { 
      position:absolute; 
      top:0; bottom: 20px; left:0; right:0px;
      padding:0; border:0;
      margin:auto;
      height:20px; width:50px;
    }
    

    and this HTML:

    Text

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