CSS Specificity

Joel Ross

LIS 549

In this video...

  • Determining selector specificity

Specificity

If two rules "conflict" (they specify different values for the same property), then the more specific rule wins.

If two rules are equally specific, the later rule wins.

Class selectors are more specific than tag selectors.

p { /* tag selector, less specific */
  color: blue;
}

.husky { /* class selector, more specific */
  color: purple;
}
<p class="husky">
  This paragraph will be purple because the class 
  selector is more specifc, so overrides the other.
</p>

Counting Specificity

For a combined or complex selector, you can determine the specificity by counting the number of "selector parts" of each type (id, class, element):

/* 1x element selector */
p {  }

/* 2x element selector */
nav a {  }

/* 3x element selector */
ul li a {  }

/* 1x class selector  */
.highlighted {  }

/* 1x class, 1x element selector */
p.alert {  }
/* 2x class, 2x element selector */
div.alert.success strong {  }

/* 1x id, 1x element selector */
#side-nav a {  }

/* Items in a group selector are 
 * counted separately! */
/* 1x class selector; 
 * 2x class, 1x element selector */
.green, p.alert.success {  }

Comparing Specificity

"Which is more specific" is determined by comparing the counts (id first, then class, then element). The highest number wins.

#side-nav a {  } /* (1, 0, 1) */

div.alert.success strong {  } /* (0, 2, 2) */

p.alert {  } /* (0, 1, 1) */

.highlighted {  } /* (0, 1, 0) */

ul li a {  } /* (0, 0, 3) */

nav a {  } /* (0, 0, 2) */

p {  } /* (0, 0, 1) */

Comparing Specificity

If two rules are equally specific (have the exact same counts), then the later rule wins.

.alert { 
  background-color: red;
} 

.highlighted { 
  background-color: yellow;
}
<p class="alert highlighted">
  This paragraph will be yellow. Both selectors apply,
  but the later rule will override the earlier one.
</p>

Don't worry about specificity

Most "semantic" CSS is written to be appropriate specific. People tend to talk about rules in increasingly specific order naturally. You won't often have rules that override each other intentionally.


But if you find a rule not applying because it isn't specific enough... then make it a little more specific! Add an addition class or element to the selector to bump it up! 

lis549-css-specificity

By Joel Ross

lis549-css-specificity

  • 479