The Cascading Conflict
As CSS stylesheets grow, styles conflict. A developer writes a class to change a button background, but the color remains unchanged because a different selector overrides it.
To resolve these conflicts, developers often use !important, which quickly ruins the cascade structure.
Understanding how browsers calculate CSS Specificity is essential to avoid stylesheet bugs.
CSS Rule: Never use
!importantto resolve specificity conflicts. It creates styling traps that are hard to debug in large projects.
The Specificity Weighting Algorithm
Browsers evaluate selector specificity using a four-digit numeric weighting system (A, B, C, D):
- 1.A (Inline Styles): Styles declared directly on HTML elements. Weight: 1000.
- 2.B (ID Selectors): E.g.
#dashboard. Weight: 100. - 3.C (Classes and Attributes): E.g.
.btn,[type="text"]. Weight: 10. - 4.D (Elements and Pseudo-elements): E.g.
div,::before. Weight: 1.
| Selector Example | A, B, C, D Score | Total Specificity |
|---|---|---|
#dashboard .btn | 0, 1, 1, 0 | 110 |
.main-content p span | 0, 0, 1, 2 | 12 |
div | 0, 0, 0, 1 | 1 |
Specificity Code Comparison
/* High specificity selector */
#navbar .menu-item a {
color: #00e5ff; /* Weight: 100 + 10 + 1 = 111 */
}
/* Low specificity class selector */
.link-primary {
color: #7c4dff; /* Weight: 10 = Will be ignored! */
}By writing flat, class-based CSS selectors and avoiding ID tags for styling, you keep specificity low and maintainable.