Specificity Hierarchy

Every Selector has a position in the Hierarchy, which is described below:

  • Inline style: Inline style has the highest priority, as it is directly applied with the help of style attribute.
  • Identifiers(ID): ID has the second highest priority, in comparison to the Class or Element Selector.
  • Classes, pseudo-classes, and attributes: Classes, pseudo-classes, and attributes have a medium level of specificity.
  • Elements and pseudo-elements: Elements and pseudo-elements have the lowest priority. 

Example: This example illustrates the level of specificity according to their hierarchy.

HTML
<!DOCTYPE html>
<html>

<head>
    <style type="text/css">
        h1 {
            background-color: red;
            color: white;
        }

        #second {
            background-color: black;
            color: white;
        }

        .third {
            background-color: pink;
            color: blue;
        }

        #second1 {
            color: blue;
        }

        .third1 {
            color: red;
        }
    </style>
</head>

<body>
    <h1 id="second" class="third">
        ID has highest priority.
    </h1>
    <h1>
        Element selectors has lowest priority.
    </h1>
    <h1 class="third">
        Classes have higher priority
        than element selectors.
    </h1>

    <h2 style="color: green;" 
        id="second1"
        class="third1">
        Inline CSS has highest priority.
      </h2>
</body>

</html>

Output:

Specificity Hierarchy



CSS Specificity

CSS Specificity of the Selectors can be determined when more than one set of CSS rules applies to the same element, the browser will have to decide which specific set will be applied to the element. This set of rules that the browser follows is collectively called Specificity.

Similar Reads

CSS Specificity Rules

1. Inline CSS...

Specificity Hierarchy

Every Selector has a position in the Hierarchy, which is described below:...