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

THIS DIV is in the center of the parent div. We used following CSS declaration to align this 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

THIS DIV is in the center of the parent div. We used following CSS declaration to align this 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!

Comments 3

  • Useful, nifty trick that I like and use a lot. Especially useful for layouts with fixed-width content that is always centered. Works everytime 🙂

  • 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 🙂

  • 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.

Leave a Reply

Your email address will not be published. Required fields are marked *