


We use cookies to improve your experience
We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience.
Definition
CSS specificity is the algorithm browsers use to determine which CSS rule applies when multiple rules target the same element. Specificity is calculated based on the types of selectors used: inline styles override IDs, IDs override classes, and classes override element selectors.
Every CSS selector has a specificity score expressed as four components: inline styles (1,0,0,0), IDs (0,1,0,0), classes/attributes/pseudo-classes (0,0,1,0), and elements/pseudo-elements (0,0,0,1). A selector like #header .nav a has specificity (0,1,1,1) — one ID, one class, one element. When two rules target the same element, the one with higher specificity wins. If specificity is equal, the last rule in source order wins.
Specificity wars occur when developers use increasingly specific selectors to override each other, leading to bloated, fragile CSS. A rule like div#app .container ul li a.active has very high specificity and is nearly impossible to override without !important. The !important declaration overrides all specificity, but using it frequently creates its own override war. These patterns are a major source of CSS bugs in large projects.
Keep specificity low and flat. Use single classes for most styling (.card, .button-primary) rather than long selector chains. Avoid IDs for styling (use classes instead). Never use !important except for utility classes or third-party overrides. Methodologies like BEM (.block__element--modifier) enforce low-specificity selectors by convention. CSS Modules and Tailwind CSS sidestep specificity entirely by scoping or inlining styles. Understanding specificity is fundamental to writing maintainable CSS.