what is specificity in css

11 months ago 23
Nature

Specificity in CSS is an algorithm used by browsers to determine which CSS declaration is the most relevant to an element, which in turn determines the property value to apply to the element. The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element. Specificity is calculated based on the number of selectors of each weight category in the selector matching the element (or pseudo-element) . The following are the categories that define the specificity level of a selector, in order of increasing specificity:

  • Type selectors: These are selectors that target an HTML element by its tag name, such as p, div, or h1. They have the lowest specificity value.

  • Class selectors: These are selectors that target an HTML element by its class attribute, such as .my-class. They have a higher specificity value than type selectors.

  • ID selectors: These are selectors that target an HTML element by its ID attribute, such as #my-id. They have a higher specificity value than class selectors.

  • Inline styles: These are styles that are applied directly to an HTML element using the style attribute. They have the highest specificity value.

When two or more CSS rules apply to the same element, the browser will decide which specific set will be applied to the element based on their specificity values. The selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element. Its important to note that specificity only applies when the same element is targeted by multiple declarations in the same cascade layer or origin, and only matters for declarations of the same importance and same cascade origin and layer that has precedence for the property.