Does background-color by default take on the entirety of the viewport if set on the body tag?

Viewed 76

I have the following HTML:

<body class="page">
</body>

and tied to that selector, the following rule:

.page {
    background-color: #2A2C2F;
}

enter image description here

From what the above picture shows, the body element takes up its containing elements' width (naturally, as it is a block level element) and has no height. Even with this being the case however, I see that the entirety of the viewport takes on the background-color that I have set. According to this freeCodeCamp article, the background-color only affects the content area and padding of an element (although I wonder if we can change that with the box-sizing rule).

Why is it that even without a height, the viewport seemingly takes on the background-color?

1 Answers

Short answer - yes, if the <html> tag has no background color.

From CSS-tricks:

In the absence of a background on the html element, the body background will cover the page. If there is a background on the html element, the body background behaves just like any other element.

You can also read more about it from the spec on CSS backgrounds.


Consider the following two snippets:

  1. No background color on <html>, body background color stretches to fill the canvas.

body {
  background-color: #2a2c2f;
  color: white;
}
content here

  1. Background color on <html>, body background color is restricted to the content within the body tag.

html {
  background-color: white;
}

body {
  padding: 10px;
  background-color: #2a2c2f;
  color: white;
}
content here

Related