Specificity

What is Specificity?

Specificity is the algorithm used by the browser to determine which CSS rules apply to an element. It is calculated based on the selectors used, the order of the selectors, and the number of ID selectors in the selector. The more specific the selector, the higher its specificity value.

By default, every new rule assigned to an element gets added to the previous rules. If a rule is stated twice and both selectors has an equal specificity, the last one will be used.

<nav>
  <a href="#" class="nav-link">Link 1</a>
  <a href="#" class="nav-link active">Link 2</a>
  <a href="#" class="nav-link">Link 3</a>
</nav>
+
.nav-link {
  display: block;
  padding: 8px;
  margin-right: 2px;
  /* The new rule overwrites 
  the previous one */
  margin-right: 12px;
  color: lightgreen;
}

/* Both .nav-link and .active have an equal 
specificity, so the last one will be used */
.active {
  color: deeppink;
}

Specificity hierarchy

From most to least specific, here is the specificity hierarchy:

<h1>Heading 1</h1>
<p>A generic paragraph</p>
<p class="orange">A paragraph with a class</p>
<p class="orange" id="red">A paragraph with a class and an ID</p>
+
#red {color: red;}
.orange {color: orange;}
p {color: burlywood;}
* {color: darkgray;}

Heading 1

A generic paragraph

A paragraph with a class

A paragraph with a class and an ID

Combining selectors

Specificity can also be increased by using combinators, like > or +. See "Common combinators and separators" for more.

Debugging specificity

Every browser allow you to inspect the content and styling of any element on the page. Every rule overwritten by a later or more specific rule will usually be crossed out. Chrome and Firefox will also show you the specificity score of each selector when you hover over it.