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

  1. Inline style attribute on the element itself
  2. Id selectors such as #header
  3. Class, attribute, and pseudo-class selectors such as .card, [disabled], and :focus
  4. 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.

SelectorScore (a, b, c)
a0, 0, 1
.link0, 1, 0
.post .link a0, 2, 1
#content a1, 0, 1
style="..."1, 0, 0, 0 (inline)

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.