Technically, your inner DIV (#container
) is centered horizontally. The reason you can't tell is because with the CSS width: auto
property the inner DIV is expanding to the same width as its parent.
See this fiddle: http://jsfiddle.net/UZ4AE/
#container {
width: 50px;
height: auto;
margin: 0 auto;
padding: 10px;
position: relative;
background-color: red;
}
In this example, I simply set the width of #container
to 50px
and set the background to red
so that you can see that it is centered.
I think the real question is "How do I center elements horizontally with CSS?" and the answer is (drum roll please): it depends!
I won't do a full rehash of the myriad ways to center things with CSS when W3Schools does it so nicely here: http://www.w3schools.com/css/css_align.asp but the basic idea is that for block level elements you simply specify the desired width and set the left and right margins to auto
.
.center {
margin-left: auto;
margin-right: auto;
width: 50px;
}
Please note: This answer only applies to block level elements! To position an inline element, you will need to use the text-align: center
property on the first block parent.