QuestionsHTML/CSS

Specificity and the cascade

Cascade & SpecificityMediumHTML/CSS

Two rules set the same property on one element. How does the browser decide the winner?

What it tests

Whether you can compute specificity and know where source order and !important fit in.

Approach & answer

When multiple declarations target an element, the cascade resolves them in order: (1) origin & importance, (2) specificity, (3) source order. Specificity is a tuple (a,b,c): a = number of IDs, b = classes + attribute selectors + pseudo-classes, c = element types + pseudo-elements. Compare left to right — one ID (1,0,0) beats any number of classes (0,10,0). Inline style beats all selectors. !important jumps above normal declarations entirely (and !important conflicts are resolved by specificity among themselves). If specificity ties, the LAST matching rule in source order wins — that is why order in a stylesheet matters. The universal selector * and combinators (>, +, ~) add zero specificity. Modern escape hatches: :where() contributes zero specificity (great for low-strength defaults), :is() takes the specificity of its most specific argument, and @layer lets you order whole groups of rules regardless of selector strength. Practical advice: keep selectors flat and avoid !important so overrides stay predictable.

Use this technique when

Debugging 'my style isn't applying': inspect which rule wins, then match or beat its specificity instead of reaching for !important.

References

html