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