Search code examples
htmlcsscss-selectorscss-specificity

Do CSS combinators add specificity to a CSS selector?


The mdn article about CSS specificity states:

Universal selector (*), combinators (+, >, ~, ' ') and negation pseudo-class (:not()) have no effect on specificity. (The selectors declared inside :not() do, however.)

However my experience is that combinators do have an effect, see this example:

div > p {
  color: red;
}

p {
  color: green;
}
<div>
  <p>First Paragraph</p>
  <p>Second Paragraph</p>
</div>

So the above quote claims, that CSS combinators have no effect on specificity. If that quote is right, how is it meant then, as my code example shows the opposite?


Solution

  • The problem in your snippet is that you have two selectors(div > p) in the 1st rule and in the 2nd rule only one selector(p), therefore the 1st rule is more specific, so the article is correct.

    See the snippet below using the same 2 selectors, but the 1st having a combinator >, as they have the same specificity the latter will apply due to cascading.

    div > p {
      color: red;
    }
    
    div p {
      color: green;
    }
    <div>
      <p>First Paragraph</p>
      <p>Second Paragraph</p>
    </div>

    You can see the specificity for div p, div > p and p below

    SS