1

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.

Meredith
  • 920
  • 7
  • 16
  • 31

4 Answers4

5

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • But margin:auto is not cross browser, or is it? I remember having problems with IE with that. – Meredith Jan 08 '11 at 22:26
  • It definitely is. Probably you're confusing with `float` and/or "hasLayout" for which there are relatively [a lot](http://www.satzansatz.de/cssd/onhavinglayout.html) of IE oddities. – BalusC Jan 08 '11 at 22:31
  • I've always thought you should use auto on both left/right to make it centered (it makes sense), what is the rule saying that auto on only left or right will put it into center? And I have gotten css code from designers using "hacks" to get around IE bugs when using this technique, dunno if they suck or if it was IE6 hacks and you dont care about that browser. – stefan Mar 27 '11 at 22:20
1

remove the center tags, and set this css declaration

#main-container { margin: auto; width:800px }
Xavier Barbosa
  • 3,919
  • 1
  • 20
  • 18
0

You can use

#container{
    position:relative;
    margin: auto;
}

or, if you have a fixed width for your container, lets say 800px you can do something like

#container{
    position:relative;
    left: -400px;
    margin-left: 50%;
}
cristian
  • 8,676
  • 3
  • 38
  • 44
0

Use margin: 0 auto;, as stated above:

<style type="text/css">
html, body {
  margin: 0;
  padding: 0;
}
#main-container {
  background: black;
  width: 800px;
  margin: 0 auto;
}
</style>

And by the way, if you wish to validate as proper XHTML, you need to add type="text/css" to your style elements. In addition, there is almost no need to hide your CSS from old browsers, because almost all browsers nowadays supports CSS.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63