Utilizor
Contact Us

CSS Specificity

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied.

CSS Specificity

If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element.

Think of specificity as a score/rank that determines which style declaration is ultimately applied to an element.

Specificity Hierarchy

Every selector has its place in the specificity hierarchy. There are four categories which define the specificity level of a selector:

  1. Inline styles - An inline style is attached directly to the element to be styled. Example: <h1 style="color: #ffffff;">.
  2. IDs - An ID is a unique identifier for the page elements, such as #navbar.
  3. Classes, attributes and pseudo-classes - This category includes .classes, [attributes] and pseudo-classes such as :hover, :focus etc.
  4. Elements and pseudo-elements - This category includes element names and pseudo-elements, such as h1, div, :before and :after.

Example 1: ID vs Class

The ID selector has higher specificity than the class selector.

This text will be blue because ID wins over Class.

Example 2: Class vs Element

The class selector has higher specificity than the element selector.

This text will be red because Class wins over Element.

Example 3: Inline Style Wins

Inline styles have the highest specificity.

This text will be red because Inline Style wins over ID.

Example

/* Specificity: 0, 1, 0, 0 */
#demo { color: blue; }

/* Specificity: 0, 0, 1, 0 */
.test { color: red; }

/* Specificity: 0, 0, 0, 1 */
p { color: green; }