Centering with CSS

From Exterior Memory
Jump to: navigation, search

There are three methods to center elements using CSS.

The tricks listed here come mostly from Designing With Web Standards by Jeffrey Zeldman.


Auto Margin

#element {
    margin: 0 auto;
}

Pro: Is the most standard and easy way
Con: None (it works with all commonly browsers since Internet Explorer 6)

Negative Margin

#element {
    position: absolute;
    left: 50%;
    margin-left: -100px; /* half of width, including border and padding */
}

Con: Slightly complex
Pro: Supported in a wide range of browsers

Text Alignment

#element {
    text-align: center;
}
#element * {
    text-align: left;
}

Con: Not supported by truly compliant browsers, considered a hack
Pro: Supported by IE Windows