How to calculate specificity
- Inline styles: An inline style attribute present on an element will override any styles in external stylesheets and will have the highest level of specificity.
- IDs: Each unique ID will add to the specificity.
- Classes, pseudo-classes, and attributes: Each unique class, pseudo-class, or attribute will add to the specificity.
- Elements and pseudo-elements: Each unique element or pseudo-element will add to the specificity.
The specificity is calculated as follows:
Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element.
Let's see an example:
body #content .data { background-color: blue; }
This selector contains 1 element, 1 ID and 1 class selector, so it would have a specificity of 1,100, 10. Which means that the overall specificity of this selector is 111. So to override it, you would need to write a selector which has the specificity level larger than 111.
Equal specificity: the latest rule wins - If the same rule is written twice into the external style sheet, then the latest rule wins:
h1 {color: blue;} h1 {color: red;}
Example of Specificity in Action
Let's see a real-world example:
HTML
<div id="content" class="main"> <p class="highlight">Hello, world!</p> </div>
CSS
p { color: blue; } .main .highlight { color: red; } #content p { color: green; } p.highlight { color: yellow; }
The color of the text will be green because the #content p selector has the highest specificity. It contains 1 ID and 1 element, so it has a specificity of 1,0,1. All the other selectors have lower specificity.
The specificity can lead to confusing results if not managed properly, so it's good to keep your CSS selectors as simple as possible and avoid unnecessary complexity.