Lesson 22 / 28

Specificity

How the browser decides which conflicting rule wins.

The specificity hierarchy

From strongest to weakest: inline styles, then id selectors, then class/attribute/pseudo-class selectors, then element/pseudo-element selectors. More specific wins regardless of order in the file.

Who wins?

The #title rule wins even though it's written first — id beats class.

#title { color: red; }      /* specificity: 1 id */
.heading { color: blue; }   /* specificity: 1 class */
/* result: text is red */

Quick check: Between a class selector and an id selector on the same element, which wins?

  • Whichever is written last
  • The id selector
  • The class selector
Answer

The id selector — id selectors carry higher specificity than class selectors, regardless of source order.