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.
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 theHTML
element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values oftransparent
forbackground-color
andnone
forbackground-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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With