Search code examples
htmlcsscss-selectorscss-specificity

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;
}

Solution

  • 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 color 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.

    Add some content to your page or specify a height for body and you'll see gray.


    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 (see: 3.2. the background-color property)

    And when the background-color of the html element is transparent, the browser uses the background-color of the body element to paint the canvas.

    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.