Specificity in CSS
CSS Specificity — What It Is & How It Works
Specificity is a rule that browsers use to decide which CSS rule applies when multiple rules target the same element.
Why is Specificity Important?
When multiple CSS selectors match the same element, specificity determines which rule wins.
How Specificity is Calculated
Specificity is calculated based on the types of selectors used. It’s usually represented as a 4-part value:
| Selector Type | Weight (Points) |
|---|---|
| Inline styles | 1000 |
| ID selectors | 100 |
| Class, attribute, and pseudo-class selectors | 10 |
| Element and pseudo-element selectors | 1 |
Specificity Hierarchy Examples
| Selector | Specificity Score | Explanation |
|---|---|---|
div | 0,0,0,1 | Element selector |
.class | 0,0,1,0 | Class selector |
#id | 0,1,0,0 | ID selector |
style="..." (inline style) | 1,0,0,0 | Inline style |
div.class#id | 0,1,1,1 | Combination of all above |
Examples
/* Element selector specificity = 1 */p { color: blue;}/* Class selector specificity = 10 */.text { color: red;}/* ID selector specificity = 100 */#main { color: green;}If an element matches all three, the text will be green because the ID selector is most specific.
Important Note About !important
!importantoverrides normal specificity.Use sparingly, as it can make debugging harder.
p { color: blue !important;}Summary
| Selector Type | Specificity Value |
|---|---|
| Inline styles | 1000 |
| ID selectors | 100 |
| Class/attribute/pseudo-class | 10 |
| Element/pseudo-element | 1 |
If you want, I can help you calculate specificity for your CSS code or show examples of specificity conflicts and how to fix them!