CSS Specificity
CSS Specificity
CSS specificity determines which CSS rule is applied when multiple rules target the same element. The browser calculates a score for each selector and applies the rule with the highest specificity.
If specificity is equal, the last rule in the CSS wins.
How Specificity Works
Specificity is calculated using four levels, often written as a score:
- Inline styles – highest priority
- ID selectors (
#id) - Class selectors, attributes, pseudo-classes (
.class,[type],:hover) - Element selectors (
div,p)
Each level adds to the specificity score.
Specificity Order
From lowest to highest priority:
p /* element */ .card /* class */ #main /* id */ style="" /* inline style */
Specificity Example
Consider these rules:
p {
color: black;
}
.card p {
color: blue;
}
#content p {
color: red;
}
If the HTML looks like this:
<div id="content" class="card"> <p>Text</p> </div>
The text will be red, because the ID selector has higher specificity.
Calculating Specificity
Specificity can be written as a tuple:
- Inline styles:
(1,0,0,0) - ID selectors:
(0,1,0,0) - Class / attribute / pseudo-class:
(0,0,1,0) - Element selectors:
(0,0,0,1)
Example:
#menu .item a
Specificity score:
- 1 ID →
(0,1,0,0) - 1 class →
(0,0,1,0) - 1 element →
(0,0,0,1)
Equal Specificity
If two rules have the same specificity, the rule that appears later in the CSS is applied.
.card p {
color: blue;
}
.card p {
color: green;
}
The text will be green.
Good Practices
- Avoid overusing IDs in CSS
- Prefer class-based selectors
- Keep selectors simple and readable
- Use specificity intentionally, not accidentally
Code Challenge
Goal: Understand which rule wins based on specificity.
HTML:
<div id="wrapper" class="card"> <p>Specificity Test</p> </div>
CSS:
p {
color: black;
}
.card p {
color: blue;
}
#wrapper p {
color: red;
}
Task:
- Identify which color is applied
- Explain why that rule wins
Answer: The text is red because the ID selector has higher specificity.
What’s Next?
Next, you will learn how !important can override specificity rules.