CSS Specificity

Specificity is nothing but priority which means CSS properties are taken by browser based on weight of the selector. CSS Specificity

Specificity determines, which CSS rule is applied by the browsers. If two CSS selectors apply to the same element, the one with higher specificity wins. Every selector has its place in the specificity hierarchy. There are four categories which define the specificity level of a given selector:

Highest ————————————>>>> Lowest

  • Inline style
  • ID selector (#Container)
  • Class selector (.modal)
  • Element selector (div)

Why do we need specificity in CSS?

There’s two reasons we need specificity in CSS. One of which is obvious

  1. We need some way to tell the browser which elements should be styled
  2. We need some way to tell the browser how to resolve conflicts if an element has competing styles.

So, we know what specificity is in CSS. It’s the means by which we call out a particular element or elements for a style. We know why we need it.

Example:

<!DOCTYPE html>
<html>

<head>
    <style>
        #example {
            color: grey;
        }

        .text {
            color: purple;
        }

        p {
            color: red;
        }
    </style>
</head>

<body>

    <h2 id="example" class="text" style="color: orange;">Fullstackadda.com</h2>

</body>

</html>

Output:

CSS Specificity

Note: inline style will applied because it has highest specificity.

Example 2:

Using id selector we are changing the background color

<!DOCTYPE html>
<html>

<head>
    <style>
        div {
            background-color: red;
        }

        #heading {
            background-color: yellow;   /*Higher specificity*/  
        }
    </style>
</head>

<body>

    <div id="heading">
        Welcome to the fullstackadda.com
    </div>
</body>

</html>

Output:

Css specificity

Example 3:

For same element name the latest specified element name will be applied.

<!DOCTYPE html>
<html>

<head>
    <style>
        div {
            background-color: #FFC300;
            color: #581845;
        }

        div {
            background-color: #DAF7A6;   /*it consider latest one*/  
            color: #FF5733;
        }
    </style>
</head>

<body>
    <h2> Example of same specificity </h2>
    <div> Welcome to the fullstackadda.com </div>

</body>

</html>

Output:

  1. Specificity is nothing but priority which means CSS properties are taken by browser based on weight of the selector.

CSS Specificity CSS Specificity CSS Specificity