Specificity Calculation

Specificity determines which competing selectors have greater priority. A useful mental model is a four-part weight: inline styles, IDs, classes/attributes/pseudo-classes, and elements/pseudo-elements.

For example, #app .card p is more specific than .card p. Specificity should be kept manageable because deeply specific selectors make overrides difficult.

The !important flag overrides normal declarations but should be used sparingly because it makes the cascade harder to reason about.

Specificity Weight
Specificity Example
p {
  color: black;
}

.card p {
  color: blue;
}

#article .card p {
  color: red;
}
💡 The third selector has the highest specificity because it contains an ID, a class, and an element selector.
Key Takeaways
  • IDs carry much more specificity than classes.
  • Avoid escalating specificity to solve architecture problems.
  • Use !important only when there is a clear reason.
Knowledge Check

Which selector has greater specificity?