Search code examples
csscss-selectorscss-specificity

Scoring and ranking specificity rules


I have two competing rules in my stylesheet:

#parent > div {
    color: blue;
}

#child {
    color: red;
}

Here's the relevant HTML:

<div id="parent">
 <div id="child">What color is this text?</div>
 <div>This should just be blue</div>
 <div>Also should be blue</div>
</div>

Why is #child blue and not red?

I'm not sure if I'm applying the scoring system correctly. Here's how I did it:

  • rule #1 has an id and a tag, so its score is [0, 1, 0, 1]
  • rule #2 has only an id, so its score is [0, 1, 0, 0]
  • therefore rule #1 wins, and it's blue

But this seems wrong to me -- the first rule matches multiple elements; the second rule can only match one! So isn't the second rule more specific?


Solution

  • But this seems wrong to me -- the first rule matches multiple elements; the second rule can only match one! So isn't the second rule more specific?

    Not at all. Just because a selector matches fewer elements doesn't make it more specific.

    Selector matching is done on a by-element basis, not a by-rule basis. Since there's a more specific selector that matches your element #child, which is #parent > div, that rule takes precedence, and that's it.

    It does seem counter-intuitive, but that's just how it works. One way around this is to add #parent to your second rule:

    #parent > div {
        color: blue;
    }
    
    #parent > #child {
        color: red;
    }