Specificity in CSS Selectors

Specificity in CSS Selectors

Specificity in CSS refers to the order in which selectors in CSS take precedence. The formula to calculate Specificity is as follows.

(inline - id - class - element)

Specificity should always be calculated from the left. In order to understand this formula better, take a look at the below example.

<style>
p 
{
    color: blue;
}

div #paragraph 
{
    color: green;
}
</style>

<div>
    <p id="paragraph"></p>
</div>

The result of the above scenario would be a green colored paragraph instead of a blue colored one. Why is this? Let's calculate.

Let's consider the selector for the first style applied -> p

The specificity formula for this selector will be as follows,

(inline = 0, id = 0, class = 0, element = 1) -> 0001

Now, let's consider the selector for the second style applied -> div #paragraph

The specificity formula for this selector will be as follows,

(inline = 0, id = 1, class = 0, element = 1) -> 0101

0101 precedes over 0001 since specificity is always calculated from the left.

  • Let's take a look at another interesting example.
<style>
.hello-header 
{
    color: red;
}

div > div > h1 
{
    color: blue;
}
</style>

<div>
  <div>
    <h1 class="hello-header">Hello world</h1>
  </div>
</div>

In this case, the first selector will have a specificity of 0010 and the second selector will have a specificity of 0003. Which one do you think takes precedence?

You guessed it right! It's the first one, since specificity is always calculated from the left.

What happens if you have two selectors of the exact same specificity? Let me know in the comments below.