CSS Specificity

Sometimes some CSS rules might conflict with each other due to the same target element. The browser, in this case, has some set of rules that it can used to decide the wined among the two (or more) rules. This issue resolving the set of rules is known as Specificity.

It is like a score/rank that helps the browser determine the winning style declaration for an element. For example a universal selector (*) is treated with lower priority than the ID selectors.

Specificity Hierarchy

The selectors are divided into 4 categories to get their place decided in the specificity hierarchy.

  • Inline styles – Any styling has done directly to the target element is treated as an inline style. For eg <h1 style= “color: red”>
  • IDs – This is done by specifying the ID instead of the inline styling.
  • Classes, attributes, and pseudo-classes – There can be user-defined or in-built classes or pseudo-classes that are styled and later used by the elements that want to use this style.
  • Elements and pseudo-elements – Instead of styling the specific elements inline, we style the generic element or pseudo-element.

Calculating Specificity

Here’s how you calculate specificity:
You start with initial value as 0 now add the following points for each kind of styling:

  • Inline Styling: 1000 Points
  • ID styling: 100 Points
  • Attribute, class, pseudo-class: 10 points
  • Generic Element, pseudo-element: 1 point

Thus at the time of conflict, any rule with the greatest specificity value, will be applied to the target element.
Specificity Rules

  • Latest rule counts: In case two rules have equal specificity, the latest rule i.e. the rule that comes latter in the style sheet will be followed.
  • ID and Attribute: The ID selector is represented by a # before the id. The attribute selector can also style on the basis of id by specifying the id attribute but since the ID selector has a higher specificity, it will prevail.
  • Contextual selectors and Single element selector: The style rules present within the HTML document (under the <style> tag) will have more specificity than any external style sheet.