EMZETT.
Login

CSS specificity

In short: Specificity decides which CSS rule wins when several apply to the same element. The more precise the selector, the higher its weight.

In more detail: The browser counts three values for every selector: IDs, classes/attributes/pseudo-classes, and element names. The rule with the higher value (compared left to right) wins. On a tie the later rule counts.

In Depth

  • Examples: p = (0,0,1), .card = (0,1,0), #head = (1,0,0), nav a.active = (0,1,2).
  • Inline style: style="…" beats every selector.
  • !important: Overrides almost everything but should stay the exception because it complicates debugging.
  • Practice: Flat selectors with classes keep styles easy to override. Deeply nested selectors and IDs lead to fights.
  • Modern helpers: @layer orders rule groups independent of specificity, :where() has zero specificity.

See also: Semantic HTML