CSS Specificity Explained
Master CSS specificity rules for reliable styling.
By EMEPublished: February 20, 2025
cssspecificityselectorscascade
A Simple Analogy
CSS specificity is like a voting system. More specific rules override general rules.
Why Specificity?
- Predictability: Understand which styles apply
- Debugging: Fix style conflicts
- Maintainability: Avoid !important hacks
- Scalability: Write organized stylesheets
- Cascade: Control inheritance chain
Specificity Calculation
Specificity = (Inline, IDs, Classes+Attributes, Elements)
Examples:
h1 = (0, 0, 0, 1)
.header = (0, 0, 1, 0)
#main = (0, 1, 0, 0)
style="color: red" = (1, 0, 0, 0)
h1.title = (0, 0, 1, 1)
div.container p.text = (0, 0, 2, 2)
#nav ul li a:hover = (0, 1, 1, 3)
Example Conflicts
/* Specificity (0,0,0,1) - Element */
p { color: black; }
/* Specificity (0,0,1,0) - Class (wins) */
.highlight { color: red; }
/* Specificity (0,1,0,0) - ID (wins) */
#intro { color: blue; }
/* Specificity (1,0,0,0) - Inline (wins) */
<p style="color: green;">Text</p>
Pseudo-Classes & Elements
/* Pseudo-classes add to class specificity */
a:hover = (0, 0, 1, 1)
input:focus = (0, 0, 1, 1)
ul li:first-child = (0, 0, 1, 2)
/* Pseudo-elements add to element specificity */
p::first-letter = (0, 0, 0, 2)
div::before = (0, 0, 0, 2)
Avoiding !important
/* Bad - Hard to override later */
.btn { background: blue !important; }
/* Better - Be specific instead */
.btn { background: blue; }
.btn.primary { background: blue; }
.btn.primary:hover { background: darkblue; }
Best Practices
- Be specific enough: Don't use overly general selectors
- Avoid IDs: Use classes instead for reusability
- No !important: Use specificity instead
- Naming: Use BEM or similar system
- Organize: Group related rules together
Related Concepts
- CSS cascade
- Inheritance
- Media queries
- Responsive design
Summary
CSS specificity determines which styles win. Master the rules to write maintainable, predictable stylesheets.