CSS Specificity

Subject: css

CSS Specificity

CSS Specificity is a set of rules that determine which styles are applied when multiple selectors match the same HTML element. When more than one rule targets the same element, specificity decides which one takes precedence.

The more specific the selector, the higher its priority in applying styles.


How Specificity Works

Each selector contributes a value toward the specificity score. CSS specificity is calculated based on four categories:

  • Inline styles: counts as 1 in the first position
  • ID selectors: counts as 1 in the second position
  • Classes, attributes, and pseudo-classes: counts as 1 in the third position
  • Elements and pseudo-elements: counts as 1 in the fourth position

Specificity Calculation Formula

Specificity = (Inline Styles, IDs, Classes/Attributes/Pseudo-classes, Elements)

Examples:

  • #main-title → (0, 1, 0, 0) = 100
  • .title → (0, 0, 1, 0) = 10
  • h1.title → (0, 0, 1, 1) = 11
  • style="color: red;" → (1, 0, 0, 0) = 1000 (highest)

Example: CSS Specificity in Action

Output Explanation

The <p> tag uses all 3 selectors: p, .highlight, and #main-text, each defining the color property. The final color shown is red, because inline styles have the highest specificity.


Ways to Override Specificity

  • Be more specific in your selector (e.g., use IDs instead of classes)
  • Use !important (only when absolutely necessary)
  • Refactor CSS structure to avoid deep conflicts

Example Using !important

Even if a more specific selector exists, !important will override it.


Key Takeaways

  • Specificity determines which rule is applied when multiple rules match an element
  • Specificity order: Inline styles > IDs > Classes > Elements
  • Avoid overusing !important, as it makes debugging harder
  • Structure your CSS properly to reduce specificity conflicts and improve maintainability