jakewies jakewies - 7 months ago 13
HTML Question

Why doesn't background color on body work?

When viewing the code below in my browser the background is white. The universal selector

*
has the lowest specificity, and the
body
selector comes after the universal selector. Shouldn't it be grey?

* {
background-color: white;
}

body {
background-color: grey;
}

Answer

Let's break down the code in the question:

* {
    background-color: white;
}

body {
    background-color: grey;
}

This is saying:

  1. Select every element and make its background color white.
  2. Select the body element and make its background grey.

Well, if the universal selector says select all elements, this would include the root element (html).

So the code computes to:

html {
    background-color: white;
}

body {
    background-color: grey;
}

The root element paints the canvas white, and the body element has no height, so the canvas remains white.


Observation made in the comments:

Interesting. But if we eliminate the * from the equation and just have the body, the page will be grey with or without height being specified. I don't quite understand why that is.

So if we eliminate the universal selector, what happens to the background-color of the root element?

It resets to its initial value: transparent.

And when the background-color of the html element is transparent, here's what happens:

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.

source: https://www.w3.org/TR/css3-background/#body-background

In other words, if the root element's background-color is transparent, then the browser uses the background-color of the body element to paint the canvas.