Specificity, Cascade and Inheritance
When two rules give different values to the same element, which one wins? CSS decides in this order:
This is the lesson that explains "why isn't my CSS working?". Usually, another rule is winning. Open DevTools (F12), select the element, and look at the Styles panel: rules that lost are shown crossed out, with the winning rule above them. Understanding specificity turns this from frustrating guesswork into a quick fix.
- Importance -
!importantbeats normal rules (use it very rarely). - Specificity - the more specific selector wins.
- Order - if they are equally specific, the rule written later wins.
Specificity scores
- Inline
style="..."- strongest #id- 1-0-0.class,:hover,[type=email]- 0-1-0p,h1,::before- 0-0-1
Compare from left to right. #menu a (1-0-1) beats .nav a.link (0-2-1), because one id beats any number of classes.
Example
<!DOCTYPE html>
<html>
<head>
<style>
p { color: black; } /* 0-0-1 */
.price { color: green; } /* 0-1-0 wins over p */
#special { color: purple; } /* 1-0-0 wins over .price */
.price.sale { color: red; } /* 0-2-0 loses to #special */
</style>
</head>
<body>
<p>Black text</p>
<p class="price">Green price</p>
<p class="price sale">Red sale price</p>
<p class="price sale" id="special">Purple, because the id wins</p>
</body>
</html>▶ Try it yourselfInheritance
Some properties pass down from parent to children: color, font-family, font-size, line-height. Others do not: border, margin, padding, background. That's why setting a font on body changes the whole page.
Example
body { font-family: system-ui, sans-serif; color: #1f2937; line-height: 1.6; }
button { font: inherit; } /* buttons don't inherit fonts by default */Keep specificity low and even: style with classes, avoid ids in CSS, and avoid
!important. Then your rules are easy to override later.Key points
- Importance, then specificity, then order decide which rule wins.
- id beats class beats element.
- Some properties inherit (color, font), others don't (margin, border).
- Keep selectors simple; avoid !important.
📝 Test yourself
1. Which selector is more specific?
2. Two rules have the same specificity. Which wins?
3. Which property is inherited by child elements?
