I've got an problem. I have the html code like this:
<div id="main_content" >
<div id="container">
</div>
</div>
The css like this:
#main_content {
top: 160px;
left: 160px;
width: 800px;
min-height: 500px;
height: auto;
background-color: #2185C5;
position: relative;
}
#container {
width: auto;
height: auto;
margin: 0 auto;
padding: 10px;
position: relative;
}
I suppose that the #container will be centered within #main_content. However, it is not. I just want to find out the reason and how to make it centered.
try to get the
position:relative;
in you#container
, add exact width to#container
working demo
Technically, your inner DIV (
#container
) is centered horizontally. The reason you can't tell is because with the CSSwidth: auto
property the inner DIV is expanding to the same width as its parent.See this fiddle: http://jsfiddle.net/UZ4AE/
In this example, I simply set the width of
#container
to50px
and set the background tored
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
.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.Now just define your
#main_content
text-align:center
and define your#container
display:inline-block;
as like this
use
margin:0 auto;
to the child div. Then you can center the child div inside the parent div.If you set
width: auto
to a block element, then the width would be 100%. So it really doesn't make much sense theauto
value here. Really the same for height, because by default any element is set to an automatic height.So finally your
div#container
is actually centered but it just occupy the whole width of its parent element. You do the centering right, you need just to change the width (if needed) to see that it is really centered. If you want to center your #main_content then just applymargin: 0 auto;
on it.Another interesting way: fiddle
css
html