CSS ยท Chapter 31 of 44

CSS Specificity

Specificity determines which CSS rule wins when multiple rules target the same element. It's calculated from the number of ID, class, and element selectors used, roughly in that order of weight.

Inline styles beat all selectors, and !important overrides normal specificity rules entirely (though it should be used sparingly).

Syntax
/* #id (100) > .class (10) > element (1) */

Specificity hierarchy

From weakest to strongest: element selectors < class/attribute/pseudo-class selectors < ID selectors < inline styles < !important.

Calculating specificity

Specificity is often written as a tuple (IDs, classes, elements). More IDs beat more classes; more classes beat more elements.

Example 1 (css)
p { color: black; }
.text { color: blue; }
#main { color: red; }
Output
An element with id='main' and class='text' shows red text (ID wins)

ID selectors have higher specificity than class selectors, which beat element selectors.

Key points

  • Specificity is based on ID, class, and element selector counts.
  • IDs outweigh classes; classes outweigh element selectors.
  • Inline styles override all normal selectors.
  • !important overrides specificity entirely, so use it sparingly.
๐Ÿ’ก Note: When specificity ties, the rule that appears later in the stylesheet wins.

๐Ÿ“ Quick Quiz

1. Which selector type has the highest specificity (excluding inline/!important)?

2. What overrides specificity entirely?

3. When two rules have equal specificity, which wins?