Search code examples
csscss-selectorscss-specificity

Specificity / inheritance of color from asterisk / body?


I am little confused with the following css

* {
    color: yellow;
}
body {
    color: black;
}

and HTML

    <div>
        <p> Test text... </p>

    </div>

any "p" under the body, would get a color of yellow - but why ? The asterisk has not got a weight.

and color is inherited so why doesn't the color of my "p" takes its color from the body ?

Instead it uses the color from the asterisk.

I mean, if a "body" and "p" (and anything in the line of inheritance) doesn't have a color then it should use the asterisk.

Can anyone help ? why the above is the way it is.

The chunk of html above gets a color of yellow but why does it not have black (which comes from the body) ?


Solution

  • I mean, if a "body" and "p" (and anything in the line of inheritance) doesn't have a background-color then it should use the asterisk.

    The asterisk is a part of a selector that means "any element", not a special rule that means the properties within are applied as defaults when they have no inherited or specified value.

    For example, another way to match body (but also head) would be:

    html > * {
        …
    }
    

    because body is an element (*) that is a child of (>) an element named “html” (html).

    So your body rule applies a background color to the body, but your * rule applies a background color to the p.

    (Background color is also not an inherited property, but it doesn’t matter in this case. color would behave the same.)