Why does “position: absolute; left: 0; right: 0; width: XYpx; margin: 0 auto” actually center?

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.)

Leave a Comment