Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




CSS - Specificity


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.


Example of Specificity in CSS


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>


Output :




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.


Example of Specificity with three CSS rules


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.


Example :



<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>


Output :




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.


Specificity Order in CSS


Below are the specificity order :

  1. Inline style


    This has the highest specificity as it is applied directly to the HTML elements.

    Example :

    <div style="color: red;"> </div>

  2. ID Selectors


    This has the second highest specificity.


    Example :

    #specificity_id

  3. Class Selectors


    This has the third highest specificity.


    Example :

    div.specificity_example

  4. Attribute Selectors


    This has the fourth highest specificity.


    Example :

    [type="text"]

  5. Element Selectors


    This has the fifth and lowest priority.


    Example :

    div