Jeremy Waraksa Jeremy Waraksa - 4 months ago 15
CSS Question

Can't figure our why CSS specificity isn't working

So I have the following code:

<ul class="shopping-list" id="awesome">
<li><span>Milk</span></li>
<li class="favorite" id="must-buy"><span class="highlight">Sausage</span></li>
</ul>
<style>
ul#awesome {
color: red;
}
ul.shopping-list li.favorite span {
color: blue;
}
</style>


According to the CSS specificity rules (https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/) the word "Sausage" should be red, however it is appearing blue. Why?

The specificity value of "ul#awesome" = 0101
The specificity value of "ul.shopping-list li.favorite span" = 0023
So then why is the word sausage still blue?
From my understanding order of style declarations only matters if the specificity is the same for each declaration which is not the case here.

Answer

The span is inheriting the rule ul#awesome from the ul element. The rule ul.shopping-list li.favorite span directly selects the span element. Inherited rules have a specificity of 0, so any rule that selects the element itself will win.

You can test this by replacing your second rule with the basic element selector for "span", and you'll see that both Milk and Sausage are blue in that case.