Search code examples
xhtmlhtmlxhtml-transitional

Right way to center a <div> in xhtml?


Im working with a XHTML 1.0 Transitional doctype html file, and I want to have a main div with 800px width and make it appears centered (not the div content, but the div itself).

I've used this on the past:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <style>
            <!--
            html, body { margin:0; padding:0; }

            #main-container { background:black; width:800px; }
            -->
        </style>
    </head>
    <body>
        <center>
            <div id="main-container">
                Content
            </div>
        </center>
    </body>
</html>

But I am not sure if this is cross-browser compatible, or if its valid xhtml.


Solution

  • The center tag is deprecated since 1998. You need to apply CSS margin 0 auto; on the div. This will set top and bottom margin to 0 and left and right margin to auto which will let the div "auto-center" itself when its width is known/fixed.

    See also: