开发者

Centering a div in Google Chrome

I have the following CSS:

html, body {
        background-color:black;开发者_开发技巧
        font-family:"arial bold";
        overflow:auto;
        text-align: center; 
    }
div#content {
        width:792px;
        height:100%;
        padding:0px;
    }

div#header  {
        height:216px;
        width:100%;
    }

The HTML code I have is:

<html>
    <head>
        <title>
            Think in a NEW BOX.
        </title>

        <link rel="stylesheet" type="text/css" href="styles/default.css" />
    </head>
    <body onload="">
        <div id="content">
            <div id="header">
                <img src="images/title-1.png" /><img src="images/title-2a.png" /><img src="images/title-3.png" />
            </div>
        </div>
    </body>
</html>

Now, this works great in IE. The div centers perfectly (header). In Google Chrome, however, the div is left aligned. Am I missing something?


I had this 'problem' too today. Solved it with using display: inline-block;. Working browsers won't change and if it's already working, this won't mix up IE old.


You are missing:

  1. A doctype (so IE is emulating bugs from the IE 4/5 days to cope with awful, ancient webpages)
  2. That a div element is a block element so text-align does not influence it
  3. auto left and right margins on the div.

See Centring using CSS for a longer explanation with diagrams


Even better solution is to center the block like this:

#content 
{
  margin:0px auto;
}

This method is used by... well, just about everyone (including SO).


Use

#content {
    margin-left: auto;
    margin-right: auto;
    width: 100px; /* Your width */
}

to center your div. It allows your div to choose a variable margin for left and right, that results in a centered div. This should work for all browser.


Make sure you have a fixed width and use margin: 0 auto;.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜