Skip to content
Related Articles

Related Articles

Improve Article
CSS | Specificity
  • Last Updated : 15 Jan, 2019

When more than one set of CSS rules apply to the same element, the browser will have to decide which specific set will be applied to the element. The rules the browser follows are collectively called Specificity

Specificity Rules include:

    Inline CSS>Internal CSS>External CSS

  • CSS style applied by referencing external stylesheet has lowest precedence and is overridden by Internal and inline CSS.
  • Internal CSS is overridden by inline CSS.
  • Inline CSS has highest priority and overrides all other selectors.

Example:




<html>
  
<head>
    <link rel="stylesheet" type="text/css" href="external.css">
    <style type="text/css">
        h1 {
            background-color: red;
            color: white;
        }
          
        h2 {
            color: blue;
        }
    </style>
</head>
  
<body>
    <h1>
        Internal CSS overrides external CSS
    </h1>
    <h2 style="color: green;">
        Inline CSS overrides internal CSS
    </h2>
</body>
  
</html>

“extenal.css” of Example-1:






h1{
    background-color: lightgreen;
}
h2{
    color: pink;
}

Output:

inline internal and external css

Specificity Hierarchy :Every element selector has a position in the Hierarchy.

  1. Inline style: Inline style has highest priority.
  2. Identifiers(ID): ID have the second highest priority.
  3. Classes, pseudo-classes and attributes: Classes, pseudo-classes and attributes are come next.
  4. Elements and pseudo-elements: Elements and pseudo-elements have lowest priority.

Example-2:




<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 gfg

Specificity Hierarchy


Note:
  • When two or more selectors have equal specificity, the last(latest) one counts.
  • Universal selectors like body and inherited selectors have least specificity.



My Personal Notes arrow_drop_up
Recommended Articles
Page :