π What is CSS Specificity?
CSS specificity is a scoring system the browser uses to decide which CSS rule wins when multiple rules target the same element. Think of it as a priority system β the rule with the higher specificity gets applied. π
π§ Why Specificity Matters?
Without understanding specificity, your styles may not apply as expected. Mastering it helps you write clean, predictable, and maintainable CSS. π‘
π Specificity Weight Calculation
Specificity follows a 4-level numeric format:
| Selector Type | Specificity | Example |
|---|---|---|
| Inline Styles | 1,0,0,0 | <div style="color:red"> |
| ID Selectors | 0,1,0,0 | #hero |
| Class / Pseudo-class / Attribute | 0,0,1,0 | .btn, :hover, [type="text"] |
| Element & Pseudo-element | 0,0,0,1 | div, h1, ::before |
π― How Specificity Works
1οΈβ£ Inline Styles
Always the highest priority (except !important). π₯
Inline Style Example
<p style="color: blue;">This wins!</p>2οΈβ£ ID Selectors
Very powerful β use sparingly to avoid overly strong selectors.
ID Selector Example
#title {
color: green;
}3οΈβ£ Class, Pseudo-class & Attribute Selectors
These are the most common selectors and have moderate specificity β ideal for scalable CSS. β¨
Class Selector Example
.btn {
background: black;
color: white;
}4οΈβ£ Element & Pseudo-element Selectors
Lowest specificity β useful for base styles.
Element Selector Example
p {
font-size: 16px;
}βοΈ When Selectors Compete
The browser compares specificity and applies the rule with the higher score.
Competing Selectors
p { color: black; } /* specificity: 0,0,0,1 */
.text { color: blue; } /* specificity: 0,0,1,0 */
#main { color: red; } /* specificity: 0,1,0,0 */Final color applied to the element: red π₯ (ID wins)
β οΈ Understanding !important
The !important flag overrides normal specificity rules. But use it carefully β it can make your CSS harder to maintain. β
Using !important
p {
color: blue !important;
}Note
π§© Tips for Managing Specificity
- Keep selectors short and simple β¨
- Avoid chaining too many classes (e.g., .card .header .title)
- Use IDs sparingly β prefer classes for styling
- Organize CSS with a methodology (BEM, ITCSS, etc.)
- Never rely on !important as a default solution
π Real-World Example
Letβs see how specificity decides the final output:
Example
h1 { color: black; }
.title { color: blue; }
#mainTitle { color: red; }
If an element is <h1 id="mainTitle" class="title">, the text becomes red. (ID wins again) π₯