Specificity in CSS is like the priority. Let's say, if there are two CSS rules defined for a single element then the CSS rule with the highest Priority or Specificity will get the precedence over the other.
Sounds complicated?
Let clear with the below example.
<html> <head> <style> div { color: red; } div.specificity_example { color: blue; } </style> </head> <body> <div class="specificity_example"> Example of specificity </div> </body> </html>
So, if you look at the above example, there are two CSS rules defined.
The first one is for the element selector.
div { color: red; }
And the second one is for the class selector.
div.specificity_example { color: blue; }
Now, if you see the above output, color blue is applied to the <div> element.
<div class="specificity_example"> Example of specificity </div>
That is because the class selector has higher specificity or priority over the element selector.
Let us see the next example, where we would be defining three CSS rules and see which CSS rule has the highest priority or specificity.
<html> <head> <style> #specificity_id { color: green; } div { color: red; } div.specificity_example { color: blue; } </style> </head> <body> <div id="specificity_id" class="specificity_example"> Example of specificity </div> </body> </html>
So, in the above example, we have defined three CSS rules. The first one is the ID selector, second one is element selector and third one is class selector.
#specificity_id { color: green; } div { color: red; } div.specificity_example { color: blue; }
And if you look at the above output, green color is applied to the contents of the <div> element.
<div id="specificity_id" class="specificity_example"> Example of specificity </div>
That is because the id selector has the higher priority or specificity over the element selector and class selector.
Below are the specificity order :
<div style="color: red;"> </div>
#specificity_id
div.specificity_example
[type="text"]
div