Many times CSS doesn't work even you write the correct code, you check and re-check ID and Class but still nothing works. And you get lots of warning in CSS validator. If all this happens to you then you need to understand about Specificity, Inline Style And Important Declaration in CSS. They all play a great role in deciding which rule to work and which rule not to work. So let's check them by example.
Let's play the game!
- !important declaration (with Class or ID) wins over Inline Style, Class or ID, and Tag.
- Inline Style wins over ID, Class and Tag.
- An ID selector is worth 100 units.
- A Class selector is worth 10 units.
- A Tag/Type selector is worth 1 unit.
Also see: https://www.w3.org/TR/css3-selectors/#specificity
In the following examples I have written HTML and CSS together for understanding purpose.
Tag versus Class: Class wins
p {
color: #f13e08; /*red*/
}
.blue {
color: #040652; /*dark blue*/
}
<p class="blue"> This is a paragraph </p>
Tag, Class versus ID: ID wins
p {
color: #f13e08; /*red*/
}
.blue {
color: #040652; /*dark blue*/
}
#green {
color: #0eab35; /*green*/
}
<p class="blue" id="green"> This is a paragraph </p>
ID versus !important Declaration: !important wins
p {
color: #f13e08; /*red*/
}
.blue {
color: #040652 !important; /*dark blue*/
}
#green {
color: #0eab35; /*green*/
}
<p class="blue" id="green"> This is a paragraph </p>
Tag, Class versus Inline Style: Inline Style wins
p {
color: #f13e08; /*red*/
}
.orange {
color: #f3360c;
}
<p class="orange" style="color:blue;"> This is a paragraph </p>
Tag, ID versus Inline Style: Inline Style wins
p {
color: #f13e08; /*red*/
}
#orange {
color: #f3360c;
}
<p id="orange" style="color:blue;"> This is a paragraph </p>
!important Declaration with ID fails Inline Style: !important wins
p {
color: #f13e08; /*red*/
}
#orange {
color: #f3360c !important;
}
<p id="orange" style="color:blue;"> This is a paragraph </p>
!important Declaration with Class fails Inline Style: !important wins
p {
color: #f13e08; /*red*/
}
.orange {
color: #f3360c !important;
}
<p class="orange" style="color:blue;"> This is a paragraph </p>
Comments
Post a Comment