CSS Specificity

When more than one set of CSS rules applies to the same element, the browser must decide which set to apply to the element. Specificity refers to the rules that the browser follows.

Specificity Rules include:  

  1. CSS styles that are applied by referencing an external stylesheet have the lowest precedence and are overridden by internal and inline CSS.
  2. Inline CSS takes precedence over internal CSS.
  3. Inline CSS takes precedence over all other selectors.



Specificity Hierarchy:

Every element selector has a position in the Hierarchy. 

  1. Inline style: Inline style takes precedence.
  2. Identifiers (ID): ID are the second most important.
  3. Classes, pseudo-classes, and attributes: Next up are classes, pseudo-classes, and attributes.
  4. Elements and pseudo-elements: Elements and pseudo-elements are prioritized last.




Some best practices for managing CSS specificity include using class and ID selectors sparingly, using inheritance and cascading to reduce the number of style rules, and avoiding using inline styles. It is also helpful to organize your stylesheets in a logical and structured way, such as by using a naming convention for classes and IDs.

The universal selector (*) has the lowest specificity value and matches any element in the document. This means that if you use the universal selector in a style rule, it will have a lower specificity score than any other selector, and will only be applied if there are no other conflicting style rules with higher specificity scores.

When there are conflicting style rules with different specificity scores, the style rule with the higher specificity score will be applied to the element. If two style rules have the same specificity score, the one that appears last in the stylesheet will be applied.