I think I get CSS specificity, but this particular case is throwing me:
li:first-child {color: blue} /* 3 */
div li {color: red} /* 5 [R2] */
div.widget ul#todo {color: cyan} /* 1 [R3] */
div > ul#todo .important {color: green} /* 1 */
ul li.postponed {color: inherit} /* 2 */
li + li + li {color: magenta} /* 4 */
<div class="widget">
<ul id="todo">
<li>Buy Bread</li>
<li>Learn Guitar </li>
<li class="important">Pay Bills</li>
<li class="postponed">Wash Car</li>
</ul>
</div>
I wrote the specificity of the selectors at the side.
I though the colors of the list (per line) should be
cyan
cyan
green
cyan
but it comes out as
blue
red
green
cyan
I don't understand how R2, with the smaller specificity, can override R3, with the bigger! Could someone explain it, please?
Specificity is about resolution for different rules for the same element. But here one sets for ul
(R3) and the other (R2) for li
, so the li
takes precedence in color over its parent's rule which you think coincides.
From MDN:
Specificity only applies when the same element is targeted by multiple declarations.