Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to CSS
Understanding CSS Specificity

Understanding CSS Specificity

CSS3,053 viewsBy Admin
cssunderstandingspecificity

What is Specificity?

When multiple CSS rules target the same element, specificity decides which one wins. Understanding it ends the frustration of "why isn't my CSS applying?"

The Specificity Hierarchy

Selector typeWeight
Inline style1000
ID (#id)100
Class, attribute, :hover10
Element (div, p)1

Example

p { color: blue; }              /* weight 1 */
.text { color: green; }        /* weight 10 — wins */
#main { color: red; }          /* weight 100 — wins over both */

The Cascade Tiebreaker

If specificity is equal, the last rule wins:

.box { color: blue; }
.box { color: red; }  /* red wins — comes later */

Avoid !important

p { color: blue !important; } /* overrides everything — use sparingly */

FAQs

How do I beat a stubborn rule?

Increase specificity (add a class/ID) rather than reaching for !important. More in our CSS section.

Why is !important bad?

It breaks the natural cascade and is hard to override later.