CSS centering tricks

matt lohkamp picture matt lohkamp · Sep 29, 2008 · Viewed 8.3k times · Source

My favorite equation for centering an xhtml element using only CSS is as follows:

display: block;
position: absolute;
width: _insert width here_;
left: 50%;
margin-left: _insert width divided by two & multiplied by negative one here_

There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)

edit - oops, forgot the 'negative' part of one in the margin-left. fixed.

Answer

Ris Adams picture Ris Adams · Sep 29, 2008
div #centered{
 margin: 0 auto;
}

seems to be the most reliable from my experience.