CSS - Specificity & !important

Overview

Estimated time: 10 minutes

Learn how specificity determines the winning rule and how to avoid !important driven styles.

Learning Objectives

  • Calculate relative specificity of common selectors.
  • Use !important sparingly and intentionally.

Details & Examples

Specificity

Specificity is a scoring system that determines which rule wins when multiple rules apply.

  • Inline styles: highest
  • ID selectors: high
  • Class/attribute/pseudo-class: medium
  • Element/pseudo-element: low

Despite ID rule, !important on class wins here.

Guidance

  • Prefer lowering specificity (use classes) over adding !important.
  • Reserve !important for utility overrides and debugging.

Checks for Understanding

  1. Which wins: .card p.note vs #main p?
Show answers
  1. #main p due to the ID.

Exercises

  1. Refactor a rule relying on !important into a lower-specificity override.
  2. Explain why an ID selector should be avoided in shared components.
Suggested answers
  1. Decrease specificity (use classes) or adjust cascade order to avoid !important.
  2. IDs increase specificity and make component overrides difficult.