Body's background is overflowing

Viewed 117

So i have set my body's height and width to be 100px each and given it a background color of Red and border of 10px solid black. Why instead of 100x100 red box with a black border, i see Red color all over the screen with the border having expected dimenstions.

html, body{
    height:100px;
    width:100px;
}

body{
    background-color: red;
    font-size: 60px;
    border:10px solid black;
}
<body>
</body>

2 Answers

That is weird. That's not what I would have expected, but this seems to indicate it's a known behavior, that if the background color on <html> isn't set, but the background color on <body> is, the <body> background will flood the whole <html> area.

To quote the spec:

For documents whose root element is an HTML HTML element or an XHTML html element [HTML]: if the computed value of background-image on the root element is none and its background-color is transparent, user agents must instead propagate the computed values of the background properties from that element’s first HTML BODY or XHTML body child element. The used values of that BODY element’s background properties are their initial values, and the propagated values are treated as if they were specified on the root element.

You can also see an example at that spec link that is similar to yours.

UPDATE:

RE: your other question about <html> element's propagating to the viewport's background, I think that is also answered in a nearby section of the spec, though it is a little less clear to me:

The background of the root element becomes the canvas background and its background painting area extends to cover the entire canvas.

Note canvas in this case refers to the infinite surface the page is rendered on, not the HTML5 canvas. This seems to me to describe the behavior you mentioned in a comment where the background of a <html> with a small width/height is propagated to the viewport, though why they need the additional section I quoted above, I'm not sure about. There is more info at that link if you are curious. There seems to be some overlap between sections AFAICT.

If your goal is to create a 100x100 red box with a black border, you can create a div in your html and then give the div the properties you want in your CSS.

For example,

.red-box {
    height:100px;
    width:100px;
    background-color: red;
    border:10px solid black;
}
<html>
<body>
<div class = "red-box"></div>
</body>
</html>

Related