2

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?

dippas
  • 49,171
  • 15
  • 93
  • 105
marvhock
  • 725
  • 7
  • 14

1 Answers1

2

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

dippas
  • 49,171
  • 15
  • 93
  • 105
  • Assuming "CSS selector" and "CSS rule" being the exact same, your answer might bring some confusion. However, knowing that the specificity of above rule/selector is actually defined by counting the amount of "simple selectors", helped a lot to understand. So the combinators are just not counted to the specificity declaring number. Your answer gave the crucial hint which lead me to the helpful W3C page: https://www.w3.org/TR/2018/CR-selectors-3-20180130/#specificity – marvhock Jul 01 '18 at 19:46
  • 1
    CSS rule is different than the CSS selector.. a css selector is what you choose to style.. The CSS rule is what you style (including the selector) -selector and properties – dippas Jul 01 '18 at 19:49
  • Also see [why combinators don't add specificity](https://stackoverflow.com/questions/8096829/why-do-foo-bar-and-foo-bar-have-the-same-specificity-in-css). – BoltClock Jul 09 '18 at 14:21