为什么“position:absolute; left:0; right:0; width:XYpx; margin:0 auto“实际上中心? [英] Why does "position: absolute; left: 0; right: 0; width: XYpx; margin: 0 auto" actually center?
问题描述
我对CSS很熟练,但今天我偶然发现了一个让我头疼的片段(这里 a>和此处)。
I'm pretty proficient when it comes to CSS but today I stumbled over a snippet that got me head-scratching (here and here).
我从来没有想过可以通过 margin:0 auto
居中一个绝对定位的元素,但给定的元素有一个设置的宽度,并有 left:0
和 right:0
,它实际上似乎工作:
I never thought that one can center an absolutely positioned element via margin: 0 auto
but given the element in question has a set width and there's left: 0
and right: 0
, it actually seems to work:
#parent
{
background: #999;
height: 300px;
position: relative;
width: 300px;
}
#child
{
background: #333;
height: 50px;
left: 0;
margin: 0 auto;
position: absolute;
right: 0;
width: 50px;
}
<div id="parent">
<div id="child"></div>
</div>
( JSFiddle )
我总是 left:0 和
right:0
会决定元素的宽度(100%看起来 width
在这里优先,因此使 margin:0 auto
工作。
I always thought left: 0
and right: 0
will dictate the element's width (100% of it's first relatively positioned parent) but it seems width
takes precedence here and therefore makes margin: 0 auto
work.
这是定义的行为吗?我可以在任何规格找到它吗?
Is this defined behavior? Can I find something about it in any spec? I googled around a bit but came up with nothing useful.
推荐答案
This is accounted for in section 10.3.7 of the CSS2.1 spec:
决定这些元素使用值的约束是:
The constraint that determines the used values for these elements is:
'left' margin-left'+'border-left-width'+'padding-left'+'width'+'padding-right'+'border-right-width'+'margin-right'+'right'
'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block
如果三者都不是'auto':如果'margin-left'和'margin-right' '
If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint that the two margins get equal values [...]
有趣的是,只有绝对定位的元素,这适用于 top
, height
和 bottom
使用自动边距可以垂直对中绝对定位的元素。同样,提供上述三个属性不是自动的,并且相应的边距是自动的。 (在你的情况下,这意味着 margin:auto
而不是 margin:0 auto
。)
Interestingly, only for absolutely-positioned elements, this applies to top
, height
and bottom
as well, which essentially means that it is possible to vertically center an absolutely-positioned element using auto margins. Again, this is provided that the three properties above are not auto, and the respective margins are auto. (In your case, this means margin: auto
rather than margin: 0 auto
as the latter zeroes out the vertical margins.)
这篇关于为什么“position:absolute; left:0; right:0; width:XYpx; margin:0 auto“实际上中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!