开发者

Centering a div horizontally with variable width not working in IE

I practiced to center a div without a width and found a solution that works in every common browser. But when I put this solution into real page style, it wont work in IE.

The practice solution, that works perfectly in IE, Chrome and Firefox, looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Centerbox</title>
    <link type="text/css" rel="stylesheet" href="centerbox.css" media="all" />
</head>

<body>
    <div class="centerbox-outer">
        <div class="centerbox-inner">
            <p>Sample content that is not fixed width</p>
            <p>Some more content</p>
            <form>
         开发者_开发问答       <input type="text" name="sampleinput" />
                <input type="submit" name="go" />
            </form>
        </div>
    </div>
</body>
</html>

centerbox.css

div.centerbox-outer{
    text-align: center;
    margin: 0 auto;
}

div.centerbox-inner{
    text-align: justify;
    background-color: gray;
    display: inline-block;
}

The page where it is not working with IE is here: [link removed]

Do someone have any idea, what I'm missing there?


Made some research and found a suitable solution using relative positions. This seem to work perfectly in commonly used browsers.

The style would be following:

div.centerbox-outer{
    margin: 0 auto;
    float: left;
    left: 50%;
    position: relative;
}

div.centerbox-inner{
    text-align: justify;
    background-color: gray;
    float: left;
    position: relative;
    right: 50%;
}


To center a div, use:

 margin-left: auto; 
 margin-right: auto;

in the css for the div. Also, I've found for IE, you may need to alter your DocType to an HTML 4 specification. Something like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

I do these in my pages, and they center perfectly in IE.


div.centerbox-outer is 100% width, so putting margin: 0 auto; on it does not make any sense. If anything, you should put margin: 0 auto; on div.centerbox-inner.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜