Learn to predict which CSS rule wins using specificity, and leverage inheritance to write less code.
Open this lesson in KodokonYou 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.
p {
color: gray;
}
.article p {
color: navy;
}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.
header nav a {
color: steelblue;
}
.main-link {
color: crimson;
}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.
body {
font-family: "Inter", sans-serif;
color: #1f2937;
line-height: 1.6;
}#intro { color: red; } then .text { color: blue; }. Which color applies?