Search code examples
htmlcsscss-selectors

Does the CSS direct descendant (>) not have any value in selectivity?


Given the following class declarations and code...

.foo > a { color:green; }
.bar a { color:red; }
<div class="bar">
    <div class="foo">
        <a href="#">SOME LINK</a>
    </div>
</div>

... I thought that the link would be green because, while both declarations have a class (010) and an element (001), .foo has the direct descendant selector. But alas, the link is red. Why?


Solution

  • There's no value for > for css specificity.

    Both case have 11 value for specificity:

    .foo > a { color:green; }/*specificity value is 11*/
    .bar a { color:red; }/*specificity value is 11*/
    

    In your case you may use like this to have greater specificty:

    .bar .foo > a { color:green; }/*greater specificity value is 21*/
    .foo a { color:red; }/*specificity value is 11*/
    

    Ok, I'm going add here how specificity works:

    Selector                          Specificity         Specificity in large base
    inline-style                      1 0 0 0             1000
    id selector                       0 1 0 0              100
    class,pseudo,attribute selector   0 0 1 0               10
    type selector and pseudo elements 0 0 0 1                1