gotchacssModeratepending
Gotcha: CSS specificity wars and !important escape hatch
Viewed 0 times
specificitycascadeimportantwherelayerbem
Error Messages
Problem
CSS styles not applying because of specificity conflicts, leading to !important abuse.
Solution
Understanding and managing CSS specificity:
/* Specificity hierarchy (a, b, c): */
/* a = inline styles */
/* b = ID selectors */
/* c = class/attribute/pseudo-class selectors */
/* d = element/pseudo-element selectors */
* { } /* (0,0,0) */
p { } /* (0,0,1) */
.card { } /* (0,1,0) */
p.card { } /* (0,1,1) */
#main { } /* (1,0,0) */
#main .card p { } /* (1,1,1) */
style="..." /* (1,0,0,0) - inline */
/* Same specificity = last one wins (source order) */
.btn { color: red; }
.btn { color: blue; } /* Blue wins */
/* Common mistake: over-specific selectors */
/* BAD: Hard to override */
#app .header .nav .nav-item a.active { color: red; }
/* GOOD: Low specificity, easy to override */
.nav-link.is-active { color: red; }
/* STRATEGIES TO AVOID SPECIFICITY WARS: */
/* 1. Use single class selectors */
.card-title { font-size: 1.5rem; }
/* 2. BEM naming (Block__Element--Modifier) */
.card { }
.card__title { }
.card__title--large { }
/* 3. Use :where() to zero out specificity */
:where(.card) { padding: 1rem; } /* Specificity: (0,0,0) */
/* Any class can override without specificity battle */
/* 4. Use @layer for specificity ordering */
@layer base, components, utilities;
@layer base {
a { color: blue; }
}
@layer components {
.link { color: green; } /* Wins over base */
}
@layer utilities {
.text-red { color: red; } /* Wins over components */
}
/* 5. When you MUST use !important (rare): */
/* - Utility classes (like Tailwind) */
/* - Overriding third-party CSS you can't modify */
/* - Accessibility overrides */Why
Specificity determines which CSS rules win. Understanding it prevents the !important arms race that makes stylesheets unmaintainable.
Context
CSS architecture and maintainability
Revisions (0)
No revisions yet.