CSS Specificity Hierarchy
The specificity hierarchy ranks selector types so you can predict which style will win before you ever load the page.
Every selector belongs to a tier. From strongest to weakest, the tiers are inline styles, ids, classes and attributes and pseudo-classes, and finally element and pseudo-element selectors. A single member of a higher tier outranks any number of members from lower tiers.
The Tiers From Strongest To Weakest
- Inline style attribute on the element itself
- Id selectors such as #header
- Class, attribute, and pseudo-class selectors such as .card, [disabled], and :focus
- Element and pseudo-element selectors such as h1 and ::first-line
Reading The Scores
Comparing three rules
<!DOCTYPE html>
<html>
<head>
<style>
/* (1, 0, 1) id + element */
#content a { color: teal; }
/* (0, 2, 1) two classes + element */
.post .link a { color: navy; }
/* (0, 0, 1) one element */
a { color: gray; }
</style>
</head>
<body>
<div id="content">
<a href="#">Content link</a>
</div>
<div class="post">
<div class="link">
<a href="#">Post link</a>
</div>
</div>
<a href="#">Plain link</a>
</body>
</html>The first rule wins for a matching link because its id places a 1 in the highest column, and no amount of classes in the second rule can beat a single id.
Inline Styles And Beyond
Inline style outranks the stylesheet
<!DOCTYPE html>
<html>
<head>
<style>
#note { color: purple; }
</style>
</head>
<body>
<p id="note" style="color: green;">Text</p>
</body>
</html>Note: The only thing that beats an inline style through the normal cascade is a declaration marked !important. Reaching for either is usually a sign the selectors need rethinking.