Why margin:0 auto is not aligning to center
Question by Mj1992
Several times I get this problem.Whenever I try to center something using margin:0 auto.
Sometimes i succeed and sometimes not. So my questions are.
- Why the #PostWrapper in the below example is not getting centered inside the innerWrapper.
- When does margin:0 auto works and when it doesn’t.What are the causes.
CSS:
#container #Post{
background:#FFFFFF;
border-radius:10px;
margin-top:20px;
overflow:auto;
}
#container #Post #InnerWrapper{
margin:10px;
}
#container #Post #InnerWrapper #SubjectWrapper{
overflow:auto;
}
#container #Post #InnerWrapper #SubjectWrapper #SubjectText{
font:30px "Palatino Linotype", "Book Antiqua", Palatino, serif;
font-style:italic;
font-weight:bold;
float:left;
}
#container #Post #InnerWrapper #SubjectWrapper #SubjectBox{
float:left;
margin-left:2px;
}
#container #Post #InnerWrapper #PostWrapper{
margin:0 auto;
border:3px solid #000;
display:inline-block;
}
#container #Post #InnerWrapper #PostWrapper #PostText{
font:30px "Palatino Linotype", "Book Antiqua", Palatino, serif;
font-style:italic;
font-weight:bold;
}
#container #Post #InnerWrapper #PostWrapper #PostBox{
}
HTML:
<div id="Post">
<div id="InnerWrapper">
<div id="SubjectWrapper">
<div id="SubjectText">Subject:</div>
<div id="SubjectBox"><input type="text" class="text_box" /></div>
</div>
<div id="PostWrapper">
<div id="PostText"><?php if($PageType=='and'){ echo 'Add new Deal:';}else{ echo 'Edit Company History:';}?></div>
<div id="PostBox"><textarea rows="20" cols="103" id="PostEditor" /></div>
</div>
</div>
Answer by Shomz
In short: It depends on the position
, width
and display
attributes of elements.
Try putting position: relative;
to them and also set their width.
Child divs always have a 100% width which makes centering useless, so defining width and position makes use of it. Also, you can’t use display: inline-block
, but display: block
.
EDIT
Here is the code sample of your div using margin: auto
: http://jsfiddle.net/vnAvk/
And here is with the inside elements also centerer (I think that’s what you’re after): http://jsfiddle.net/vnAvk/1/
And here’s with the whole thing centered: http://jsfiddle.net/vnAvk/2/