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.
This works nicely in all the usual browsers. As already mentioned
margin: 0 auto;
won't work in all semi-current versions of IE.The absolute positioning with 50% approach has the severe side effect that if the browser window is narrower then the element then some of the content will appear off the left side of the browser - with no way to scroll to it.
Stick to auto margins - they are far more reliable.
If you are working in Standards mode (which you should be) then they are supported in all the browsers you are likely to care about.
You can use the text-align hack if you really need to support Internet Explorer 5.5 and earlier.
just a note that the margin:auto; method only works if the browser can calculate the width of the item to be centered and the width of the parent container. in many cases setting width:auto; works, but in some it does not.
Well that seems like massive overkill, I've got to say. I tend to set the container to
text-align:center;
for old browsers,margin:auto;
for modern browsers, and leave it like that. Then reset text-align in the element (if it contains text).Of course, some things need setting as block, and widths need setting... But what on earth are you trying to style that needs that much hacking around?
Margin:auto works in all browsers as long as you make sure IE is in standards mode.
It's more picky than others and requires your doctype to be the very first in your document, which means no whitespace (space, tabs or linefeeds) before it.
If you do that, margin:auto is the way to go! :)
seems to be the most reliable from my experience.