CSS Specificity

Understand the rules that determine which style declarations are applied to an element.

What is CSS Specificity?

CSS Specificity is the algorithm used by browsers to determine which CSS rule is the most relevant and should be applied to an element. When multiple rules target the same element and conflict, specificity decides which one wins.

CSS Specificity Chart

Specificity Hierarchy

Specificity is calculated by counting the number of selectors in each of these categories (from highest to lowest priority):

  1. Inline Styles: Style applied directly to an element (e.g., <p style="color: red;">).
  2. IDs: Selectors that target an element by its unique ID (e.g., #my-id).
  3. Classes, Attributes, and Pseudo-classes: Selectors like .my-class, [type="text"], or :hover.
  4. Elements and Pseudo-elements: Selectors for element types like p, div, or pseudo-elements like ::before.

The universal selector (*) and combinators (+, >, ~, ' ') have no effect on specificity.

Example 1: ID vs. Class vs. Element

/* Element selector (low specificity) */
p {
  color: blue;
}
/* Class selector (medium specificity) */
.text-green {
  color: green;
}
/* ID selector (high specificity) */
#text-red {
  color: red;
}

This text is red because the ID selector (#text-red) has the highest specificity.

Example 2: Specificity Calculation

A selector's specificity is often represented as `(IDs, Classes, Elements)`.

/* Specificity: (0, 1, 1) */
div.box {
  background-color: lightblue;
}
/* Specificity: (0, 2, 0) */
.box.dark {
  background-color: navy;
  color: white;
}
/* Specificity: (1, 0, 0) */
#unique-box {
  border: 2px solid red;
}
This box has a navy background because `.box.dark` (0,2,0) is more specific than `div.box` (0,1,1). The red border comes from the ID.

The !important Rule

The !important declaration can be added to a style to override all other rules, regardless of specificity. It should be used sparingly as it can make debugging difficult.

Example 3: The Power of !important

#important-demo {
  background-color: red; /* High specificity */
}
.important-override {
  background-color: limegreen !important; /* Wins! */
}
This box is green because !important overrides the ID selector.

Further Reading