Welcome to the OzoneAsylum FaqWiki
Frequently Asked Questions
CSS

How do I get vertical and horizontal centering with CSS? Pages that link to <a href="https://ozoneasylum.com/backlink?for=5339" title="Pages that link to How do I get vertical and horizontal centering with CSS?" rel="nofollow" >How do I get vertical and horizontal centering with CSS?\

Horizontal Centering

In this example, <body> contains the centered element and #center is the centered element:

code:
body {
text-align: center;
}

#center {
margin-left: auto;
margin-right: auto;
text-align: left;
}



"margin-left: auto" and "margin-right: auto" is all that is needed to center an element in standards-compliant browsers.

However, it doesn't work in IE5/Win and earlier. Fortunately, there is a workaround. IE5 incorrectly centers block level elements with the property "text-align: center". So we apply "text-align: center" to the element containing the centered element, and use "text-align: left" on the centered element, in order to override the previous rule.

Also note: You should be able to replace "margin-left: auto" and "margin-right: auto" with the a shorthand such as "margin: auto" or "margin: 0 auto". The shorthands, however, are known to fail in certain versions of Opera. So it's recommended that you declare the left and right margins seperately. It may be redundant, but it's necessary redundancy.



Vertical Centering

Its vertical aligning that causes the problems. the vertical-align property will align things, like an image, in relation to the text but it is often required to vertically center whole DIVs for a layout. setting the top and bottom margins to auto should, in theory, work - but it doesn't. However, u-neek has worked out an example:

vertical and horizontal centering

vertical centering with CSS (2004-08-18 broken link)

--------------------------------
Relevant threads:

horizontal & vertical centering

Vertical Centering

Centering Opening Logo

Ozone we have a problem

--------------------------------
Relevant links:

BlueRobot's Layout Reservoir has a couple of solutions ot horizontal centering: The one with margins set to auto is my preferred solution (and is the one used here but there is also a trick using negative margins

vertical and horizontal centering - u-neek's example.

Centring - this seems to only work in Mozilla though.

A horizontal centering with some <span>'s <--- Shameless plug from Rinswind 2th
The same but now with <div>'s
--------------------------------
Relevant FAQs:

How do I get vertical and horizontal centering with JavaScript?

________________________
Emperor

(Added by: Emperor on Thu 17-Oct-2002)

(Edited by: Emperor on Thu 17-Oct-2002)

(Edited by: ozphactor on Mon 25-Aug-2003)

(Edited by: ozphactor on Mon 25-Aug-2003)

(Edited by: Emperor on Fri 10-Oct-2003)
(Edited by Tyberius Prime on 08-19-2004 03:07)
(Edited by Rinswind 2th on 03-17-2005 23:32)

« BackwardsOnwards »

Show Forum Drop Down Menu