margin-top背后的原理是什么:auto和margin-bottom:auto总和为0 margin? [英] What is the rationale behind margin-top: auto and margin-bottom: auto amounting to 0 margin?
问题描述
由于 margin-right:auto
和 margin-left:auto
但我知道这不会发生,根据CSS规格:
Yet I understand this does not happen, as per CSS specs:
如果margin-top或margin-bottom为auto,则其使用值为0.
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.
也适用于块元素:
10.6.3当溢出计算为可见时,正常流中的块级非替换元素'
当溢出不计算为可见但已传播到视口时,此部分还适用于正常流中的块级未替换元素。
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.
如果'margin-top'或'margin-bottom'为'auto',则其使用值为0.
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.
推荐答案
如上所述:
Aha ...那不是那么晦涩!我可以看到它是有用的。感谢您在jsfiddle上给出的示例。
Aha... That's not so obscure! I can see it being useful. Thanks for the example you gave on jsfiddle.
因此,如果元素相对于父元素绝对定位,则使用 top
和 bottom
,但它的 height
被定义,并且小于父元素的高度减去 top
和 bottom
偏移量,那么 margin
属性将用于确定它的垂直对齐到父级, margin:auto
将导致垂直居中的元素。
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,听起来很复杂,但在 jsfiddle / a>。
True, it sounds complicated, yet it's clear on jsfiddle.
例如,此CSS:
.inner {
position:absolute;
top:0; bottom: 20px; left:0; right:0px;
padding:0; border:0;
margin:auto;
height:20px; width:50px;
}
和此HTML:
<div class=outer>
<div class=inner>Text</div>
</div>
这篇关于margin-top背后的原理是什么:auto和margin-bottom:auto总和为0 margin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!