Jeremy Waraksa
Jeremy Waraksa

Reputation: 3

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.

Upvotes: 0

Views: 421

Answers (3)

Chris Bergin
Chris Bergin

Reputation: 415

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.

Upvotes: 1

dippas
dippas

Reputation: 60553

Specificity can be represented by 4 columns of priority:

inline = 1|0|0|0

id = 0|1|0|0

class = 0|0|1|0

element = 0|0|0|1

Left to right, the highest number takes priority.

So in your case, you have:

  • ul#awesome - 0|1|0|1 - which is not directly applied to the word.

and you have:

  • ul.shopping-list li.favorite span - 0|0|2|3 - which is directly applied to the word.

so 0|0|2|3 is more specific than 0|1|0|1 therefore it is blue and not red.

you can test the specificity of your css here


if you want to make it red using ul#awesome just add span

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

Upvotes: 2

blurfus
blurfus

Reputation: 14031

ul > li.favorite > span is more specific to the span than ul#id

Outside of the span, the outer selector would be more specific - see it in action

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

Upvotes: 0

Related Questions