Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

html - Why does "position: absolute; left: 0; right: 0; width: XYpx; margin: 0 auto" actually center?

I'm pretty proficient when it comes to CSS but today I stumbled over a snippet that got me head-scratching (here and here).

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' = width of containing block

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 [...]

As you can see, auto margins on both sides behave the same for absolutely-positioned elements as they do for non-positioned block-level elements, provided that the left and right offsets, as well as width, are not 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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...