How to position HTML element in the center using CSS.
Jan 19
CSS, Web Development cascading_style_sheet, CSS, positioning, web development tools 3 Comments
For example, if you want to put an image at the center of your header div how do you accomplish this?
There are several ways to align an element in the center but the preferred and elegant method is to use margin property.
By setting left and right margin widths to “auto” you tell the browser to put this element at the horizontal center of the the parent element.
Outer DIV
#outerDiv{
background:#fff;
border:1px solid #333;
width:450px;
}
#innerDiv{
margin:auto;
background:#eee;
width:50%
}
Piece of cake, huh? Not so fast. This approach will work in all browsers except, you guessed it, in IE6. I am sure you are not surprised that IE6 will not render this div as you would have expected. But there is a workaround for this IE6 behavior. You can set text-align property of the outer div to center and this will align your inner div nicely in the center in IE6.
This will, however, introduce a side effect. Since you are setting text-align property of the parent element to center, your inner div (the child) will inherit this property also and the text will be center-aligned. If you don’t want your text to be in the center, reset text-align property at the child level by adding text-align:left;
So your final style sheet will have this declaration.
Outer DIV
#outerDiv{
background:#fff;
border:1px solid #333;
width:450px;
text-align:center;
}
#innerDiv{
margin:auto;
background:#eee;
width:50%
text-align:left;
}
Good luck!
Related posts:



Jan 20, 2010 @ 12:42:00
Useful, nifty trick that I like and use a lot. Especially useful for layouts with fixed-width content that is always centered. Works everytime
Jan 21, 2010 @ 04:38:27
This should only work when you give the inner DIV a width, in your case I looked on the code of the page and you’re giving it width:50% if it’s not there it won’t work.
Thanks for sharing
Jan 26, 2010 @ 08:46:00
Kamel, you are correct. Without the width property the div will try to cover the whole width of the parent element. I missed this when copying the CSS fragment, I have updated the post to include the width in the sample code.
Thanks for pointing this out.