How to position HTML element in the center using CSS.
Positioning text in the center of an element is easily done using text-align:center property. But how do you position an entire element, for e.g; a div or an image in the center of the containing parent element?
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!
Veron
January 20, 2010 @ 12:42 pm
Useful, nifty trick that I like and use a lot. Especially useful for layouts with fixed-width content that is always centered. Works everytime š
Kamel
January 21, 2010 @ 4:38 am
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 š