Lesson 118 +5 XP

CSS Combinators & Specificity Cheatsheet

CSS Specificity & Cascade, the quick rules

When two styles fight, the browser picks one. Here's HOW.

Specificity scoring

Count the parts of a selector:

PartPoints
id100
class, attribute, pseudo-class10
element, pseudo-element1

Highest total wins. ``#header .nav a { }`` scores 100+10+1 = 111.

! with !important overrides everything (avoid unless needed!).

Cascade order (when ties)

  1. !important declarations.
  2. Inline style attribute.
  3. Specificity.
  4. Source order, later wins.
  5. Inherited values lose to anything.

Inheritance

Some properties are inherited (color, font-size, line-height); others are NOT (margin, padding, border, width, background). Rule: text-looks inherit, box-layout doesn't.

Control it with keywords:

  • inherit: force inherit.
  • initial: reset to default.
  • unset: inherit if normally inherited, else initial.
  • revert: back to user-agent default.

Combinators quickly

  • div p, any descendant.
  • div > p, direct child.
  • h2 + p, immediately after sibling.
  • h2 ~ p, any following sibling.

Practical tips

  • :where() adds ZERO specificity, great for resets.
  • :has() lets you style a parent based on children.
  • Keep specificity low: prefer classes over ids when theming.

TL;DR

  • IDs >> classes > elements.
  • !important beats everything (use rarely).
  • Equal specificity => later rule wins.
  • Inheritance: text yes, boxes no.
  • combinators control depth of selection.