4

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?

User 5842
  • 2,849
  • 7
  • 33
  • 51
  • Then what do you think viewport is? – Sato Takeru Jan 15 '21 at 17:48
  • @George The way I understand it is that the viewport is the part of the document that is visible which I suppose is not necessarily the same as the `body`. However, why does the `background-color` still affect it if I am only setting it on the `body`? – User 5842 Jan 15 '21 at 18:01

1 Answers1

1

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
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • 2
    The spec is at paragraphs 3 and 4 of [CSS 2.2 14.2 The background](https://drafts.csswg.org/css2/#background). Specifically the body background is propagated to the *canvas*, not the viewport. – Alohci Jan 15 '21 at 19:15
  • Thanks for the link @Alohci. – chazsolo Jan 15 '21 at 19:18