问题
So I've got a basic 2-column HTML layout that I've applied some basic CSS to:
html {
background-color: gray;
}
body {
width: 900px;
background-color: white;
margin: 0 auto;
overflow: hidden;
}
.logo, .nav, .contact {
float: left;
width: 248px;
border: 1px black solid;
}
.about, .banner, .content {
float: right;
width: 648px;
border: 1px black solid;
}
The problem is, the when I add the <!DOCTYPE html>
declaration to the beginning of my page, the background-color
attribute doesn't work for the body
tag. I assume this has something to do with it defaulting to quirks mode without the DOCTYPE, but what am I doing wrong that might be invalid CSS? (I've validated with jigsaw and it doesn't show any errors/warnings.)
回答1:
Because you were missing the DOCTYPE — which really should have been there to begin with — your page was being rendered in quirks mode. In quirks mode, browsers are known to stretch the height of body
to 100% of the height of the viewport. In standards mode, which is triggered by having an appropriate DOCTYPE, body
behaves like a regular block-level element, being only as tall as its contents by default. In your case, this results in body
's background color not being visible.
There's nothing inherently wrong with your CSS, which is why it validates, but if you want body
to stretch to the height of the viewport in standards mode, you should add the following height properties to html
and body
respectively:
html {
height: 100%;
}
body {
min-height: 100%;
}
来源:https://stackoverflow.com/questions/12125961/body-background-color-property-doesnt-work-correctly-with-html5-doctype