I have a very simple nested <div> layout:
<div id="main">
<div id="options">
<a href="#">option 1</a> |
<a href="#">option 2</a>
</div>
</div>
I applied a very simple CSS :
#main{
height:50px;
background-color: #cc00ff
}
/*here is the thing confused me*/
#options{
margin-left:auto;
width: 8em;
}
You can run it on jsfiddle here. Everything works fine. But there is one little thing confused me: which is, why the CSS code :
#options{
margin-left:auto;
width: 8em;
}
makes the options <div> to be located to the right side of the main <div> ? Anyone can explain to me the reason?
The reason is because you have set an auto margin on one side, which means it will just fill the space given it. I suppose this is the same sort of result as applying a float of right, but without any impact on document flow. It basically works out the automatic margin by removing the width left after the width of the contained elements.
If you wanted it centered you’d need to add an auto margin to both, with fills both sides of the parent with the width left over equally.