When you style the background of the body element, why does the styling affect the entire screen and not just the body element itself? Let's say I create the following rule:
body {
width: 700px;
height:200px;
border: 5px dotted red;
background-color: blue;
}
I find that the border shows up as 700px wide as I would expect, but the background color occupies the entire browser viewport. Why?
The HTML <body> background Attribute is used to specify the background-image for the document. Note: It is not supported by HTML5 Instead of using this attribute we use CSS background property. Attribute Values: It contains the value i.e URL Which specify the address of the background Image.
To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
Definition and Usage The <body> tag defines the document's body. The <body> element contains all the contents of an HTML document, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
The HTML <body> bgcolor Attribute is used to define a Background color of a Document.
Quote from http://www.w3.org/TR/CSS21/colors.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.
The body
element is the root-element, and thus, as required by the CSS rules it loses its background style and the background style is applied to the containing canvas (the webpage area in the browser), therefor the entire screen is blue. The other properties stay with the element (e.g. the border
).
From CSS: The Definitive Guide by Eric Meyer
In CSS values are never propagated upward; that is, an element never passes values up to its ancestors. There is an exception to the upward propagation rule in HTML: background styles applied to the
body
element can be passed to the html element, which is the document's root element and therefore defines its canvas.
So when you add the background-color: blue;
declaration to the body
element, this value is propagated to the html
element (which is also the root element). Add this declartion to see it for yourself.
html {
background-color: grey;
}
When you set the background color of <body>
, the browser interprets this as the background color for the entire window, even if you've forced the <body>
to be smaller with CSS. Otherwise, what color would the outside of the <body>
tag be?
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