What is the rationale behind margin-top: auto and

2019-02-19 07:07发布

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

Yet I understand this does not happen, as per CSS specs:

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.

Also applies to block elements:

10.6.3 Block-level non-replaced elements in normal flow when 'overflow' computes to 'visible'

This section also applies to block-level non-replaced elements in normal flow when 'overflow' does not compute to 'visible' but has been propagated to the viewport.

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

Now what I would like to know, is the rationale behind this decision/behavior.

What I'm searching for is understanding and conviction. I don't think a vague explanation would do it, yet any contribution is welcome.

1条回答
爷的心禁止访问
2楼-- · 2019-02-19 07:45

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:

<div class=outer>
    <div class=inner>Text</div>
</div>    
查看更多
登录 后发表回答