HTML & CSS - Mastery / CSS Basics

CSS Specificity

📌 Why Specificity Matters

CSS Specificity is a set of rules the browser uses to decide which style rule applies to an element when multiple rules could match.

When two or more CSS rules target the same element, the one with higher specificity wins (i.e., is applied).


🔢 Specificity Values (Weights)

CSS assigns points to selectors based on how specific they are. The specificity is calculated as a four-part number like a,b,c,d where:

Selector Type

Value (a,b,c,d)

Inline styles

(1,0,0,0)

ID selectors (#id)

(0,1,0,0)

Class / attribute / pseudo-class

(0,0,1,0)

Element / pseudo-element

(0,0,0,1)

Universal selector *

(0,0,0,0)

📝 The higher value from left to right wins.


📚 Examples of Specificity

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>CSS Specificity Example</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <!-- Inline style has the highest specificity -->
    <h1 id="title" class="title" style="color: red">Hello, Specificity!</h1>
  </body>
</html>
/* Inline style - specificity (1,0,0,0) */
<h1 style="color: red">Hello</h1>
# ID selector - (0,1,0,0)
#title {
  color: green;
}
# Class selector - (0,0,1,0)
.title {
  color: blue;
}
# Element selector - (0,0,0,1)
h1 {
  color: purple;
}

🎯 If all four of these applied to <h1 id="title" class="title">, the final color would be:

  • Inline wins > ID > Class > Element

    ✅ So it would be red (from inline style)


⚖️ Comparing Specificities


💡 Tips to Handle Specificity

  • Avoid overusing !important; use it only when absolutely necessary.

  • Prefer lower specificity for reusability.

  • When two selectors have equal specificity, the later one wins (source order).

  • Use developer tools to debug specificity issues.