问题
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
topandbottom, yet it'sheightis defined and is less then the height of the parent element minus thetopandbottomoffsets, then themarginproperty will be used to determine it's vertical alignment in relation to the parent, andmargin:autowill 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