Search code examples
csscss-selectorscss-specificity

CSS specificity: [parent ID] [descendant combinator (space)] [my class] more specific than [my ID]?


Is my reasoning wrong is this a valid CSS rule?

Firstly:

  1. [My ID] is more specific than [my class].

Secondly:

  1. [My ID] is more specific than [parent ID].

But:

  1. [parent ID] [descendant combinator (space)] [my class] more specific than [my ID]?

See it for yourself - JS Bin.

This really surprises me because I have never heard of this combination before, not in the Specificity Wars neither in https://www.w3.org/TR/selectors/#specificity


Solution

  • [My ID] is more specific than [parent ID]

    No, a lone ID is a lone ID. What's important in your example is which element it is being applied to.

    [parent ID] [descendant combinator (space)] [my class] more specific than [my ID]

    Yes, it's valid, and it is more specific. Using the W3C's abc model:

    #child { // 1, 0, 0 = 100 Specificity }
    
    #parent .foo { // 1, 1, 0 = 110 Specificity }
    
    #parent #child { // 2, 0, 0 = 200 Specificity }
    
    #parent #child.foo { // 2, 1, 0 = 210 Specificity }
    

    So, #parent .foo will trump #child, but #parent #child trumps #parent .foo

    #parent { /* 100 */
      color: blue;
    }
    #parent .foo { /* 110 */
      color: green;
    }
    #child { /* 100 */
      color: red;
    }
    #parent #child { /* 200 */
      color: aqua;
    }
    <div id="parent">
      <div id="child" class="foo bar">what color am I?</div>
    </div>