HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Specificity

Specificity is the set of rules applied by browsers to determine which CSS property values are the most relevant to an element and, therefore, will be applied.


The Specificity Hierarchy

Specificity is based on matching rules which are composed of different CSS selectors. The hierarchy, from highest to lowest, is:

  1. Inline styles: (e.g., style="color:red")
  2. IDs: (e.g., #header)
  3. Classes, attributes, and pseudo-classes: (e.g., .nav, [type="text"], :hover)
  4. Elements and pseudo-elements: (e.g., h1, p, ::before)

How to Calculate Specificity?

In simple terms, think of it as a score (0, 0, 0, 0):

Selector Score (Thousands, Hundreds, Tens, Ones)
Inline Style 1, 0, 0, 0
ID Selector (e.g. #test) 0, 1, 0, 0
Class / Attribute / Pseudo-class 0, 0, 1, 0
Element / Pseudo-element 0, 0, 0, 1

Practical Example

Assume we have these three rules targeting the same <p> element:

p { color: grey; } /* Specificity 0,0,0,1 */
.intro { color: blue; } /* Specificity 0,0,1,0 (WINS!) */
#main p { color: green; } /* Specificity 0,1,0,1 (OVERALL WINNER!) */

Note: If the specificity score is identical, the last rule declared in the CSS file will be applied.

Tip: The universal selector (*) and combinators (+, >, ~) have zero specificity.