Understand how the CSS cascade decides which styles win when multiple rules target the same element. Learn to calculate specificity and use it to your advantage.
When multiple CSS rules target the same element, the browser must decide which declaration wins. This decision process is called the cascade, and it follows a strict priority order:
!important author styles.Understanding the cascade is the key to debugging CSS. When a style does not apply as expected, the answer is almost always that another rule with higher specificity or later source order is overriding it.
Specificity is calculated as a three-part score, often written as (A, B, C):
| Component | What counts | Example |
|---|---|---|
| A — ID selectors | Each #id adds 1 | #header = (1, 0, 0) |
| B — Class selectors, attribute selectors, pseudo-classes | Each .class, [attr], :hover adds 1 | .nav.active = (0, 2, 0) |
| C — Element selectors, pseudo-elements | Each div, ::before adds 1 | ul li a = (0, 0, 3) |
Inline styles (the style attribute on an element) beat all selector-based rules. And !important overrides everything, including inline styles.
p = (0, 0, 1).card = (0, 1, 0)#main .card p = (1, 1, 1)div.container > ul li.active a:hover = (0, 3, 3)A single ID selector (1, 0, 0) always beats any number of classes (0, N, 0) because the A column is compared first.
<style>
/* Specificity: (0, 0, 1) */
p {
color: black;
}
/* Specificity: (0, 1, 0) — wins over element selector */
.highlight {
color: orange;
}
/* Specificity: (1, 0, 0) — wins over class selector */
#special {
color: red;
}
/* Even 3 classes (0, 3, 0) cannot beat 1 ID (1, 0, 0) */
.container .highlight .text {
color: green;
}
</style>
<div class="container">
<p class="highlight text" id="special">
What color am I? (Answer: red)
</p>
</div>Which selector has the highest specificity?