JavaScript Tutorial

CSS Specificity

When multiple conflicting CSS rules apply to the same element, the browser follows a set of rules to determine which one takes precedence.

Specificity is a concept that helps browsers decide which property value is most relevant to an element. It determines which style declaration gets applied.

Selectors have a hierarchy in terms of specificity. There are four categories that define the specificity level, listed from highest to lowest:

  1. Inline styles: Styles directly attached to the element using the style attribute. Inline styles have the highest priority.

  2. IDs: Unique identifiers assigned to elements using the id attribute. ID selectors have the second-highest priority.

  3. Classes, attributes, and pseudo-classes: These include class selectors, attribute selectors, and pseudo-classes like :focus, :hover, etc.

  4. Elements and pseudo-elements: This category includes element selectors (e.g., div, h1) and pseudo-elements like :after and :before. They have the lowest priority.

Specificity is a measure of the weight applied to a CSS declaration. It is determined by the number of occurrences of each selector type in the matching selector.

Let’s understand it with an example:-

Input:-

 

Output:-

 


Go back to Previous Course