1

Given the HTML document

<p style="margin:100px;border:1px solid red;background-color:#dff">
  Hello
</p>

the browser displays:

enter image description here

However, if the document is instead:

<body style="margin:100px;border:1px solid red;background-color:#dff">
  Hello
</body>

we instead see

enter image description here

Why is the background color of the <body> element not contained within the border of the element? For other elements, the backgrounds are contained within the border, according to the box model. Why is the body element different? Why does the background "leak" outside of the element?

Ray Toal
  • 86,166
  • 18
  • 182
  • 232

1 Answers1

2

It turns out the <body> element background special treatment is by design.

The CSS documentation at csswg.org states the following:

For documents whose root element is an HTML HTML element or an XHTML html element: 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. It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

This means that the background properties you set on the <body> element propagate onto the entire user agent canvas, as long as you do not style the <html> element with a non-transparent background-color or with a background-image.

So the right way of thinking about what appears to be strange behavior, especially if you are debugging your CSS in a Developer Tools window is as follows:

  1. The styling of the body element is done properly, just like any other element.

  2. Since there is no actual HTML element that corresponds directly to a user agent canvas, the background styling of the root <html> element applies to the user agent canvas. However, the CSS designers allow that you do not have to style the <html> element; you can instead put background properties on the <body> element, and those will be applied not only to the body, but to the entire canvas.

A neat shorthand, perhaps, but it can lead to confusion since the margin, padding, and border properties of the body make it obvious the body and the canvas are not the same thing! The background handling appears different, but in reality relies on a technical rule requiring some sleuthing in the documentation to discover.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • FWIW, overflow is the only other property with similar propagation behaviour, albeit it's propagated to the viewport rather than the canvas. – Alohci Jun 08 '19 at 21:30