CSS Specificity

Understand how CSS decides which styles are applied when multiple rules target the same element.

What is CSS Specificity?

CSS Specificity is a rule system that browsers use to decide which CSS style should be applied when multiple styles target the same HTML element.

  • Prevents style conflicts
  • Defines priority between selectors
  • Helps browsers choose the final style
  • Essential for writing clean CSS

Real-Life Example: Imagine 3 people giving instructions — the boss’s order has higher priority than others. CSS works the same way.

Why CSS Specificity is Important

Without specificity rules, browsers wouldn’t know which style to apply when conflicts occur.

  • Avoids unexpected UI behavior
  • Makes debugging easier
  • Improves CSS readability
  • Reduces overuse of !important

CSS Specificity Hierarchy

CSS follows a priority order when applying styles:

  • Inline styles (highest priority)
  • ID selectors
  • Class, attribute, pseudo-class selectors
  • Element and pseudo-element selectors (lowest priority)

Important: The more specific the selector, the higher its priority.

Understanding Specificity Score

Specificity is calculated using a four-part value:

  • Inline styles → (1,0,0,0)
  • ID selectors → (0,1,0,0)
  • Class / attribute / pseudo-class → (0,0,1,0)
  • Element / pseudo-element → (0,0,0,1)

Tip: Higher numbers win from left to right.

Specificity Example

Conflicting CSS Rules


p {
    color: blue;
}

.text {
    color: green;
}

#message {
    color: red;
}

                

Result: The text color will be red because ID selectors have higher specificity than class and element selectors.

Inline Style vs CSS File

Inline Style Example


This text is purple

Explanation: Inline styles override all external and internal CSS rules.

The !important Keyword

The !important keyword forces a CSS rule to override all other rules.

Using !important


p {
    color: blue !important;
}

#demo {
    color: red;
}

                

Warning: Overusing !important makes CSS hard to maintain.

Common CSS Specificity Mistakes

  • Overusing ID selectors
  • Depending too much on !important
  • Writing overly complex selectors
  • Ignoring selector hierarchy

Best Practices for CSS Specificity

  • Prefer class selectors
  • Keep selectors simple
  • Avoid inline styles
  • Use !important only when unavoidable

Pro Tip: Clean CSS is easier to scale, debug, and maintain.