Toolspark
📖How-To Guides--6 min read

CSS Specificity Explained: How Browsers Decide Which Styles Win

Learn how CSS specificity works, how to calculate it, and why your styles sometimes get overridden. Practical examples and tips for writing maintainable CSS.

cssweb developmentfrontendspecificitydeveloper tools

What Is CSS Specificity?

When multiple CSS rules target the same element, the browser needs to decide which one wins. This is where specificity comes in. Specificity is a scoring system that determines which CSS declaration takes priority.

Think of it as a tiebreaker. The more specific a selector is, the higher its priority.

How Specificity Is Calculated

Specificity is represented as four numbers: (a, b, c, d)

LevelWhat countsExamples
aInline stylesstyle="color: red"
bID selectors#header, #nav
cClasses, attributes, pseudo-classes.active, [type="text"], :hover
dElements, pseudo-elementsdiv, p, ::before

Examples

/* Specificity: 0,0,0,1 */

p { color: blue; }

/* Specificity: 0,0,1,0 */

.text { color: green; }

/* Specificity: 0,1,0,0 */

#title { color: red; }

/* Specificity: 0,1,1,1 */

#nav .link a { color: orange; }

/* Specificity: 1,0,0,0 - always wins (except !important) */

<p style="color: purple">

In the example above, if all these rules target the same

element, the inline style wins because it has the highest specificity.

Common Pitfalls

The !important Escape Hatch

Adding !important overrides all specificity calculations. But using it creates problems:

/* This always wins, regardless of specificity */

p { color: red !important; }

/* The only way to override an !important is another !important

with higher specificity - this gets messy fast */

#main p { color: blue !important; }

Avoid !important whenever possible. If you need it, your selectors probably need refactoring.

Selector Order Matters (When Specificity Ties)

When two selectors have identical specificity, the one that appears later in the stylesheet wins:

.button { background: blue; }   /* Same specificity: 0,0,1,0 */

.primary { background: green; } /* This wins because it comes later */

Combinators Do Not Add Specificity

The space ( ), >, +, and ~ combinators do not affect specificity. They define relationships between selectors but add no weight.

Practical Tips

1. Keep specificity low - Prefer classes over IDs in selectors

2. Use BEM or similar naming - .block__element--modifier keeps specificity flat

3. Avoid nesting more than 3 levels deep - Each level adds specificity debt

4. Never use !important in component styles - Reserve it for utility overrides only

5. Use our CSS Specificity Calculator to compare selectors side by side

Tools to Help

📖 Related Articles