Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

How CSS resolves conflicts: the specificity rule

There are two main ways of how CSS deals with conflicting rules: specificity and cascading. In this article, we will focus on specificity.

Take the following example:

div p { color: green;}
p { color: red;}     

Applied to this HTML:

<body id="home-page" class="blog">
    <div class="intro">
        <p> some content</p>

The cascading rule in CSS will indicate that the paragraph should be reb, given the last rule. However, we will see that the paragraph is green. And that is because of the first rule is more specific than the last rule.

ok, but what happens if we have a CSS like this one: { color: green;}
.intro .blog p { color: blue; }
#home-page { color: orange;}
body div p { color: red;}      

With the HTML being the same, what color will the paragraph be in this case?

How CSS specificity is calculated?

The CSS power can be determined by calculating the sum of all the selectors that are used in that statement. For this we can use the following table:

The most powerful selectors are the ID's (100 specificity points) , followed by classes (10 specificity points), and finally the elements selectors (just 1 specificity points each).

The pseudo-class selectors (for example :hover, :before or :after) and the attributes selectors have the same power as a class selector (10 points).

So, with this knowledge, let's calculate the specificity levels in our example: { color: green;}
// one ID and one CLASS
// #home-page(100) + .blog(10)  = 110

.intro .blog p { color: blue; }
// two CLASS and one ELEMENT
// .intro(10) + .blog(10) + p(1) = 21

#home-page { color: orange;}
// one ID 
// #home-page (100) = 100

body div p { color: red;}       
// three elements  
// body(1)  + div(1) + p(1) = 3    

So the first rule gets the most specificity power, with 110 points making the text green colored.

Also, keep in mind that specificity is more powerful than cascading. However, if we have conflicting rules, with the same specificity then the result will be determined based on the cascading / order.


div p { color: green;}
// div (1) + p (1)  = 2

body p { color: blue; }
// body(1) + p (1)  = 2

// same specifity; the last rule wins
// paragraph is blue

What about the specificity of !important and inline styles

In normal circumstances, we should avoid as much as possible to use both !important and inline styles. But if we have to, keep in mind that inline styles count as 1000 points, and !important is even more powerful with 10.000 points.

So the full table of specificity points looks like this:

Alright friends, that's all for now! Have a fantastic day šŸ™‚

Home Screencasts Best of Newsletter Search X