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

∥☆過路亽.° 提交于 2019-12-01 08:00:24

问题


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:


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>    


来源:https://stackoverflow.com/questions/12386739/what-is-the-rationale-behind-margin-top-auto-and-margin-bottom-auto-amounting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!