frosty
frosty

Reputation: 2649

Changing the background color and width of the body element

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

Answers (1)

Michael Benjamin
Michael Benjamin

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> Element

For documents whose root element is an HTML HTML element or an XHTML html element: if the computed value of background-image on the root element is none and its background-color is transparent, user agents must instead propagate the computed values of the background properties from that element's first HTML BODY or XHTML body child element. The used values of that BODY 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 the BODY element rather than the HTML element.

Upvotes: 4

Related Questions