Why does adding a DOCTYPE affect my CSS?

2020-03-28 05:40发布

I am wondering why the following HTML/CSS renders fine until I put a doctype in:

<body style="margin:0; padding:0; background-color:#eeeeee"></body>

<div id="HeaderContainer" style="background-color:#eeeeee; color:Black; border-bottom:1px solid #cccccc; height:60px; margin:0px"></div>

<div style="width:100%; background-color:White; margin:0px; padding:0px">

<div style="margin:30px; width:840px; margin:10px auto; margin-top:50px; background-color:#cc0000;">

text

</div>

</div>


</div>

</body>

What I want is a header (a grey bar) with a dark grey border at the bottom. Beneath this, I want my content, which goes into a big 100% width div that's white (as the page is grey). The above code looks fine, but if I add this line to the top:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The margin on the innermost div turns from white to grey, so the page looks wrong.

Can anyone explain why? I am testing this using IE8 but it looks the same in Chrome.

Image description:

woo

标签: html css
3条回答
我只想做你的唯一
2楼-- · 2020-03-28 06:09

Adding a DOCTYPE declaration causes the browser to render the page in [almost] standards mode instead of quirks mode.

查看更多
▲ chillily
3楼-- · 2020-03-28 06:21

you are closing the body tag on line 1 and and then again on the last line.

查看更多
神经病院院长
4楼-- · 2020-03-28 06:27

This is terribly formed XHTML.

The problem you are referring to is actually a webkit issue. When you use a margin on an element, it uses the background from the parent element in the margin space. Instead use padding to get past this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title></title>
    </head>
    <body style="margin:0; padding:0; background-color:#eee">
        <div id="HeaderContainer" style="background-color:#eee; color:#000; border-bottom:1px solid #ccc; height:60px; margin:0px"></div>
        <div style="width:100%; background-color:#fff; margin:0px; padding:0px">
            <div style="width:840px; margin:0 auto; padding-top:10px; background-color:#c00;">
                text
                <br /><br /><br />
            </div>
        </div>
    </body>
</html>
查看更多
登录 后发表回答