开发者

Right way to center a <div> in xhtml?

开发者 https://www.devze.com 2023-02-03 00:35 出处:网络
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).

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 cr开发者_Python百科oss-browser compatible, or if its valid xhtml.


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:

  • Center a div in CSS, (text-align is not the answer)


remove the center tags, and set this css declaration

#main-container { margin: auto; width:800px }


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%;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号