Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving background-color to body applying whole page. Why?

Tags:

html

css

body {
  background-color: red;
}
<body>
  <div>Hello World!</div>
</body>

So the background-color: red; applies to whole page height but when I inspect the page the height of the body is only up to the div containing Hello World!.

Someone please explain this why it is happening like this.

like image 478
Mr_Perfect Avatar asked Jun 01 '17 06:06

Mr_Perfect


2 Answers

The main reason is because the HTML takes the background-color of BODY since:

The background of the root element becomes the background of the canvas and covers the entire canvas [...]

So since the default background-color of HTML is transparent it will take the one from BODY. However applying a color to both the HTML and BODY elements you will see that the BODY background doesn't cover the whole page anymore.

html {
  background-color: blue;
}

body {
  background-color: red;
}
<html>

<body>
  <div>Hello World!</div>
</body>

</html>

The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for background-position) at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of transparent for background-color and none for background-image, user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element. Such backgrounds must also be anchored at the same point as they would be if they were painted only for the root element.

From W3 - 14 Colors and Backgrounds.

like image 86
Paolo Forgia Avatar answered Sep 29 '22 11:09

Paolo Forgia


CSS tricks has a related post in merit link . It seems that body styles are expanded to html because:

html is the root element of a document where body is a descendent contained within it. In fact, there is a :root selector in CSS. These target the exact same thing

like image 40
itacode Avatar answered Sep 29 '22 11:09

itacode