Specificity in CSS
In CSS, specificity is the measure of how specific a selector is in selecting an element or group of elements on a web page. Specificity is determined by the number and type of selectors used in the CSS rule, and it determines which CSS rule is applied to an element when multiple rules target the same element.
A selector's specificity is calculated based on the following criteria:
The number of ID selectors: Each ID selector increases the specificity by 100.
The number of class selectors, attribute selectors, and pseudo-class selectors: Each of these selectors increases the specificity by 10.
The number of element selectors and pseudo-element selectors: Each of these selectors increses the specificity by 1.
#navbar a { color: blue; } // 101 points
.navbar a { color: pink; } // 11 points
.navbar .nav:hover a { color: red; } // 31 points
#navbar .nav[type='text'] a { color: black; } // 121 points
a { color: green; } // 1 point
Formula: (no. of ID selectors) * 100 + (no. of class selectors) * 10 + (no. of type selectors) * 1
CSS Rule having the highest point is applied to the element.
Inline CSS overrides all of the properties mentioned above.
!important overrides inline css. However using either of them is not a good practice as they make it difficult to understand and maintain the code.
Final rule: !important > Inline CSS > ID > Class > Tag.