Reputation: 2649
I'm trying to set the background for the body
element. I've changed the width of body
, and I expect the background to fit in this width, but instead it's filling the whole screen. How would I fix it?
body {
border: 1px solid black;
width: 500px;
margin: 0 auto;
background: black;
}
Upvotes: 2
Views: 2042
Reputation: 371539
You're actually doing it, except when you don't declare a background color for the html
element, it then takes the background color of the body
element. Hence, you're not seeing the difference.
Simply give the html
element a different background color, and also give body
some height
:
html {
background-color: red; /* new */
}
body {
border: 1px solid black;
width: 500px;
height: 500px; /* new */
margin: 0 auto;
background: black;
}
Understanding the relationship between html
, body
and background-color
.
The initial background-color
for all elements is transparent
.
If the background-color
of the html
element is not specified (i.e., transparent
) then, under the rules of CSS, the browser gives it the background-color
of the body
element.
From the spec:
3.11.2. The Canvas Background and the HTML
<body>
ElementFor documents whose root element is an HTML
HTML
element or an XHTMLhtml
element: if the computed value ofbackground-image
on the root element isnone
and itsbackground-color
istransparent
, user agents must instead propagate the computed values of the background properties from that element's first HTMLBODY
or XHTMLbody
child element. The used values of thatBODY
element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for theBODY
element rather than theHTML
element.
Upvotes: 4