Selectors, Specificity and the Cascade

Learn how the browser decides which rule wins when several target the same element, and how to write selectors that stay predictable.

Beginner · about 4 hours · difficulty 2/5

Learn first: HTML Document Essentials

CSS stands for Cascading Style Sheets, and the cascade is the algorithm that resolves conflicts. Most "CSS is broken" moments are really cascade misunderstandings.

Selectors

  • Type (p), class (.card), id (#main), attribute ([type="email"]).
  • Combinators: descendant (.nav a), child (>), sibling (+, ~).
  • Pseudo-classes describe state (:hover, :focus-visible, :nth-child(2n), :not()); pseudo-elements create virtual parts (::before, ::placeholder).

How a winner is chosen

  1. Origin and importance: user-agent styles, then yours; !important flips priority.
  2. Cascade layers (@layer): earlier layers lose to later ones regardless of specificity.
  3. Specificity: counted as (ids, classes/attributes/pseudo-classes, types). #a beats .b.c.d. :where() contributes zero; :is() takes its most specific argument.
  4. Source order: if everything else ties, the later rule wins.

Inheritance is separate: properties like color and font-family pass to children, while margin and border do not. inherit, initial, unset and revert let you control it.

Habits that scale

  • Style mostly with single classes; avoid ids and deep descendant chains.
  • Treat !important as a smell except in utility layers.
  • Use DevTools' Styles pane: it shows crossed-out losing declarations and why.

Move on when you can predict, before refreshing, which of two conflicting rules applies, and explain it using specificity or order.

Key concepts

  • Basic and attribute selectors
  • Combinators
  • Pseudo-classes and pseudo-elements
  • Specificity calculation
  • Inheritance and inherit/unset/revert
  • :is(), :where() and :not()
  • Cascade layers (@layer)
  • DevTools Styles pane

Mini project

Create a specificity quiz page: ten pairs of conflicting rules with a hidden answer for each, then verify every answer in DevTools.

Check yourself

Which wins and why: .nav .link.active or #header a?

Free resources