I am confused about size of body tag in html.
I have a tough code as follows:
<body>
</body>
body{
padding: 0px;
height: 100px;
background-color: #e5e5e5;
}
Why does background cover all of the page?, I thought it should only cover 100px,
Please explain this for me, thank for your help!
To set the background color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color.
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. Syntax: <body background="URL">
The HTML bgcolor attribute is used to set the background color of an HTML element.
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 ).
This is indeed confusing, but it is specified in the CSS 2.1 specification, clause 14.2 Background: if the computed value of background-color
is transparent
and the computed value of background-image
is none
for the html
element (as things are by default), browsers must instead use the computed value of the background properties for the body
element and must not render a background for body
(i.e. make it transparent). That is, body
background magically turns to html
background if html
lacks a background of its own – and this only affects background properties, not the true height of the body
element.
I haven’t seen any rationale for this odd rule, which prescribes a kind of “reverse inheritance”. But it’s clearly specified in CSS 2.1 and applied by browsers.
As explained in other answers, you can make your content have a background of specific height either by setting a background on html
(so that body
background is really applied to body
only) or by using wrapper element inside body
and setting height on it (since the special rule applies to body
only).
Thanks to Anne van Kesteren who pointed to the CSS spec when I asked about this in the WHATWG mailing list. (I thought I knew CSS 2.1 by heart but really didn’t. ☺)
The body is a special HTML tag, and ordinarily covers the entire HTML page. Try the following:
<body>
<div id="content">
Content goes here
</div>
</body>
and the CSS to accompany it would be:
body{
/* whatever body related codes you'd like to use go here */
}
#content{
padding: 0px;
height: 100px;
background-color: #e5e5e5;
}
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