๐ฏ CSS Specificity – Mastering Style Conflicts Like a Pro
CSS is powerful—but when multiple styles target the same element, things can get confusing fast. That’s where specificity comes in.
This guide explains everything in a structured, visual, and practical way—with examples, math intuition, and real-world tips.
๐ Table of Contents
- What is Specificity?
- Core Rule
- Specificity Math
- Worked Example
- Code Example
- CLI Output
- Important Rules
- Common Pitfalls
- Key Takeaways
- Related Articles
๐ง What is CSS Specificity?
Specificity decides which CSS rule wins when multiple rules apply to the same element.
๐ Core Principle
\[ \text{Most Specific Rule Wins} \]
Browsers calculate a score for each selector and apply the highest one.
๐ Specificity Formula (Easy Math)
\[ Specificity = (1000 \times Inline) + (100 \times ID) + (10 \times Class) + (1 \times Element) \]
Explanation:
- Inline styles → 1000
- ID selectors → 100
- Class / pseudo-class → 10
- Elements → 1
๐ Example Breakdown
div#container .content h2:hover {
color: purple;
}
Calculation:
\[ 100 (ID) + 10 (class) + 10 (pseudo-class) + 1 (element) = 121 \]
| Selector Type | Value |
|---|---|
| #container | 100 |
| .content | 10 |
| :hover | 10 |
| h2 | 1 |
๐ป Code Example
p { color: blue; }
#intro { color: green; }
.intro-text { color: red; }
p:hover { color: yellow; }
๐ฅ️ Result (Simulated Browser Output)
Click to View Result
Normal state → Green (ID wins) Hover state → Yellow (pseudo-class applied)
๐ Important Rules
- Inline styles dominate
- ID > Class > Element
- Selectors add up
- !important overrides everything
⚠️ Common Mistakes
- Overusing IDs → Hard to override later
- Deep nesting → Too complex
- Using !important everywhere → Maintenance nightmare
๐ก Key Takeaways
- Specificity is a scoring system
- Math helps predict behavior
- Keep selectors simple
- Avoid unnecessary complexity
๐ฏ Final Thought
Once you understand specificity, CSS stops feeling random—and starts feeling predictable.
No comments:
Post a Comment