When CSS rules disagree, specificity helps settle the argument. If competing declarations come from the same style source and target the same element, the browser gives greater weight to the selector that targets more specifically. section 19.22 section 19.30
Think of each selector as collecting points. More targeted selectors earn more points, so their declarations win over less targeted competitors. The cascade first compares where declarations come from; specificity breaks ties among declarations from the same source. section 19.28 section 19.30
Use this scoring recipe for a selector:
- Give 1 point for each element or pseudo-element, such as p, div, or ::before. section 19.28
- Give 10 points for each class or pseudo-class, such as .colored-text or :hover. section 19.28
- Give 100 points for each ID. Inline styles receive 1,000 points. section 19.28
- Count the universal selector (*) as 0. Adding !important gives a declaration 10,000 points and the greatest CSS weight. section 19.28
Four rules, one paragraph
For <p class="colored-text"> inside a div, p.colored-text scores 11: one point for p and 10 for .colored-text. It beats .colored-text (10), div p (2), and p (1), so the paragraph text is purple. This is why a rule that seems like it should apply can lose to a more specific selector. section 19.29 section 19.28
<style>
p.colored-text {
color: purple;
}
.colored-text {
color: blue;
}
div p { #1
color: green;
}
p { #2
color: red;
}
</style>
<div>
<p class="colored-text">What is the color of this text?</p>
</div>
Compare the four selectors against the same paragraph, then total each selector’s points before checking the winning color. section 19.28
Specificity is useful for debugging: when a style does not appear, look for another rule targeting the same element with more weight. IDs deserve caution because their high specificity can make CSS harder to maintain and troubleshoot. section 19.29 section 19.5





