Centering

From CSS Standards FAQ

Jump to: navigation, search

Contents

Horizontally

To horizontally center a block level element use:

#element_id { margin: 0 auto }

Important Note: auto value for margins will NOT center floated element or element with { position: absolute; } applied to it. See Further Reading section if that's the case.

margin is just a shorthand, element gets centered when both left and right margins are set to value auto.

This method requires to have a width set on the element with a unit value that (or less then 100%) and that the browser is rendering your page in standards mode. You can ensure the latter by providing a proper Doctype. The reason for width requirement is because otherwise block-level element will be as wide as the container. If you need fluid width (aka shrink wrap) see Centering Block-level Content With Unknown Width tutorial.

Note that Internet Explorer 5 doesn't support margin:0 auto, but will let you center anything using text-align:center on the parent element.


To center inline elements and text, use text-align: center on the container

#parent_id { text-align: center }

Note: Internet explorer suffers from a bug, text-align property also centers block-level elements, more info about the bug on hasLayout.net Text-Align Bug tutorial

Vertically

To vertically center a block level element you can set a percentage padding or margin on the top of your element; also, you can use position absolute, depending on your circumstances, to set it 50% down. Hypothetically, you can display an element as a table cell and use vertical-align, but this is not supported in Internet Explorer, however it is still possible to hack around that, see http://zoffix.com/new/css-vertical-center.html for an example as well as Further Reading section below.

With the position property

To position an element horizontally with the position property, absolute value must be given and have a parent element that is set to `relative` property value. For example the following will horizontally centre the div element with the identifier bar within foo. Please note that by assigning 50% from left indicates the starting location of the element, therefore margin-left with half the negative width of bar will compensate for the difference.

<div id="foo">
    <div id="bar"></div>
</div>

#foo { position:relative; }
#bar { 
    position:absolute; 
    top:0;
    left:50%;
    width:50%;
    margin-left:-25%;
}

Similarly, we can vertically position an element with top: 50%; and left: 0, however setting a fixed height unit (i.e. px) is not encouraged as the contents within the element may vary.

Further Reading

Personal tools