Kodokon kodokon.com

Cascade, specificity, and inheritance

Learn to predict which CSS rule wins using specificity, and leverage inheritance to write less code.

8 min · 3 questions

Open this lesson in Kodokon

You write a rule, reload the page… and nothing changes. Most of the time, the culprit isn't a bug: it's the cascade. When several rules target the same element, the browser breaks the tie in this order: the rule's origin (browser styles, then yours), the selector's specificity, and finally the order of appearance in the code. Mastering this mechanism will save you hours of debugging.

CSS
p {
  color: gray;
}

.article p {
  color: navy;
}
Both rules target the same paragraph: the more specific one wins.

Specificity is calculated as a three-part score: (ids, classes, elements). #menu scores 1-0-0, .nav-link scores 0-1-0, a scores 0-0-1. You compare from left to right: #menu (1-0-0) beats .nav .link .active (0-3-0), even with three classes. Mental exercise: which wins between header nav a (0-0-3) and .main-link (0-1-0)? The class, because a class outweighs any number of elements.

CSS
header nav a {
  color: steelblue;
}

.main-link {
  color: crimson;
}
The link with .main-link will be red: 0-1-0 beats 0-0-3.

Inheritance is your ally for writing less code: text-related properties (color, font-family, font-size, line-height) are automatically passed down to descendants. Box properties (margin, padding, border, width) are not inherited - thankfully, otherwise every child would receive its parent's border. So define your typography once, at the highest level.

CSS
body {
  font-family: "Inter", sans-serif;
  color: #1f2937;
  line-height: 1.6;
}
Three declarations on body are enough for the whole page.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Two rules target the same paragraph: #intro { color: red; } then .text { color: blue; }. Which color applies?
    • Blue, because the class is declared last
    • Red, because an id is more specific than a class
    • Neither, the browser reports a conflict
  2. Which of these properties is inherited by descendant elements by default?
    • margin
    • color
    • border
    • padding
  3. Two selectors have exactly the same specificity and target the same element. Which rule wins?
    • The rule written last in the stylesheet
    • The rule written first
    • The rule with the shortest selector