Search code examples
selectorcss-specificity

CSS Specificity rule


According to what I read about css specificity the following example should gives it the color Red but the true answer is blue.

Highest => lowest

Style , ID, class/psuedoclass/attr, Element

ul#awesome has 101
ul.shopping-list li.favorite span has 23

Where am I wrong?

<ul class="shopping-list" id="awesome">
    <li><span>Milk</span></li>
    <li class="favorite" id="must-buy"><span class="highlight">Sausage</span></li>
</ul>
What is the color of the text Sausage ?

ul#awesome {
    color: red;
}
ul.shopping-list li.favorite span {
    color: blue;
}

Solution

  • CSS uses the most specific styling first and if that doesn't exist it keeps getting more general until it finds a styling that applies, i.e. styling applied to a <p> tag gets overwritten by styling applied to a <a> tag nested within the <p> tags.

    In your case the red is applied to the un-ordered list as a whole, and the blue is applied to the specific list item which overwrites the formatting of the overall list. The red will only be used if the list item doesn't have its own formatting.