If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element.
Think of specificity as a score/rank that determines which style declaration are ultimately applied to an element.
Look at the following examples:
<style>
p{color:red;}
</style>
<p>Hello World!</p>
Now, let's look at another example:
<style>
.test{color:green;}
p{color:red;}
</style>
<p class="test">Hello World!</p>
AND, another example:
<style>
#demo{color:blue;}
.test{color:green;}
p{color:red;}
</style>
<p id="demo" class="test">Hello World!</p>
Last example:
<style>
#demo{color:blue;}
.test{color:green;}
p{color:red;}
</style>
<p id="demo" class="test" style="color:pink;">Hello World!</p>
Every CSS selector has its place in the specificity hierarchy.
There are four categories which define the specificity level of a selector:
- Inline styles - Example: <h1 style="color: pink;">
- IDs - Example: #navbar
- Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
- Elements and pseudo-elements - Example: h1, :before
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.
Note: Inline style gets a specificity value of 1000, and is always given the highest priority!
Note 2: There is one exception to this rule: if you use the !important rule, it will even override inline styles!
The table below shows some examples on how to calculate specificity values:
| Selector | Specificity Value | 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) |
Consider these three code fragments:
A: h1
B: h1#content
C: <h1 id="content" style="color: pink;">Heading</h1>
- The specificity of A is 1 (one element selector)
- The specificity of B is 101 (one ID reference + one element selector)
- The specificity of C is 1000 (inline styling)
h1 {background-color: yellow;}
h1 {background-color: red;}
div#a {background-color: green;}
#a {background-color: yellow;}
div[id=a] {background-color: blue;}
#content h1.red {background-color: red;}
#content h1.yellow {background-color: yellow;}
.intro {background-color: yellow;}
h1 {background-color: red;}