Introduction
Understanding CSS specificity and the !important
rule is crucial for managing styles efficiently. Specificity determines which CSS rule takes precedence, while !important
overrides specificity.
1. CSS Specificity Explained
CSS specificity is a ranking system that decides which style is applied when multiple rules target the same element.
Specificity Calculation
Each selector type has a weight:
- Inline styles (e.g.,
style="color: red;"
) → 1000 - ID selectors (
#id
) → 100 - Class, attribute, and pseudo-class selectors (
.class
,[type="text"]
,:hover
) → 10 - Element and pseudo-element selectors (
div
,h1
,::before
) → 1
Example Calculation:
#header { color: blue; } /* Specificity: 100 */
.navbar { color: red; } /* Specificity: 10 */
h1 { color: green; } /* Specificity: 1 */
CSSSince #header
has the highest specificity, its styles are applied.
2. Resolving Conflicts with Specificity
Higher Specificity Wins
p { color: black; } /* 1 */
.text { color: blue; } /* 10 */
#unique { color: red; } /* 100 */
CSSHere, #unique
wins since it has the highest specificity.
Equal Specificity: Last Rule Wins
p { color: green; }
p { color: purple; }
CSSThe second rule applies because it appears later in the stylesheet.
3. The !important
Rule
!important
forces a style to override all others, ignoring specificity.
Example:
p { color: black !important; }
#special { color: red; }
CSSEven though #special
has higher specificity, !important
makes color: black;
take effect.
When to Use !important
- As a last resort when specificity adjustments fail
- In utility classes (e.g., Bootstrap)
When to Avoid !important
- When it makes debugging harder
- When better specificity handling is possible
Conclusion
CSS specificity helps manage style conflicts, while !important
is a powerful but risky tool. Understanding both ensures cleaner, maintainable styles.