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