CSS specificity determines which rule set is to be applied if there are multiple CSS rules pointing to the same element.
CSS selectors are provided with different values and if multiple CSS rules are pointing to the same element then on the basis of those selector values CSS rules are ranked.
The specificity value on the basis of selectors ranges from 0 to 1000.
On the basic of different selectors specificity value is given as follows:
- inline style - Inline style has highest value of specificity among other selectors.Its is 1000. Can be represented as ( 1, 0, 0, 0)
- id - Id has second highest specificity value.Its is 100. Can be represented as ( 0, 1, 0, 0)
- class,pseudo-class,attribute selector - These have third highest value of specificity among other selectors.Its is 10. Can be represented as ( 0, 0, 1, 0)
- element or pseudo element - These have lowest specificity value.Its is 1. Can be represented as ( 0, 0, 0, 1)
Calculation of specificity
specificity is calculated on the basis of values given as we have mentioned above. For multiple numbers the selector value is added together.
Here in this example class will be applied to p because specificity for element rule is 1+1(two elements)=2 but specificity of class is 10(1 class)+1(1 element)=11.
Here in this example id will be applied to p because specificity for id rule is 100(1 id)+1(1 element)=101 but specificity of class is 10(1 class)+2(2 element)=12.
Here in this example inline style will be applied to p because specificity for inline rule is 1000(inline) but specificity of id is 100(1 id)+1(1 element)=101.
When there are two CSS rules having the same Specificity value then the rule that is defined lower in the style sheet is applied.