April 28, 2012

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.

  1. Why the #PostWrapper in the below example is not getting centered inside the innerWrapper.
  2. 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/

Answer by Starx

The problem is ambiguous selector, the selector chain you provided is invalid. Just use

#PostWrapper{
     margin:0 auto;
     border:3px solid #000;
     display:inline-block;
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!