CSS specificity reference
1 May 2022 (Updated 8 September 2022)
In a nutshell
Selector | Score |
Element (e.g., p , div ) | 1 |
Class (e.g., .app-header , .main-menu ) | 10 |
ID (e.g., #main-button , #testimonials ) | 100 |
Inline style (e.g., <div style="background: red;"> ) | 1000 |
!important (e.g., .div { color: red !important; } | Infinity (more or less) |
What if two selectors have the same specificity?
If two selectors have the same specificity, the selector that’s parsed last in the CSS will take precedence (hence why CSS stands for Cascading Style Sheets). For example, given this stylesheet:
p.small-font {
font-size: 14px;
}
p.large-font {
font-size: 40px;
}
and this HTML:
<p class="large-font small-font">Hello there</p>
The <p>
element will have a font size of 40px
because the p.large-font
style appeared after the p.small-font
style in the CSS. The ordering of the class in the HTML is irrelevant. See this JSBin for live demo.
Example calculations
Element | Specificity score | Calculation |
p | 1 | 1 |
p.test | 11 | 1 + 10 |
p#demo | 101 | 1 + 100 |
<p style=”color: pink;”> | 1000 | 1000 |
#demo | 100 | 100 |
.test | 10 | 10 |
p.test1.test2 | 21 | 1 + 10 + 10 |
#navbar p#demo | 201 | 100 + 1 + 100 |
* | 0 | 0 (the universal selector is ignored) |
Here’s a colorful illustration from specifishity.com:
Sources
Tagged:
CSS
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment