Bo dinglesTM - -   Bright Lightbulb Graphic Ideas   - -

The Web Developer Bootcamp 2024

Colt Steele

Back to CSS Reference Index


CSS Specificity

What is Specificity?

If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element.

Think of specificity as a score/rank that is determined mathematically, that calculates which style declaration is ultimately applied to an element

Think of it like this, if you have a class, let's call it tmp, with a p tag child. When trying to style p tags, the .tmp p tag would have a higher specificity, because mathematically, it is more specific.

So if you styled all p tags to green, but styled the .tmp p to red, then all of the p tags would be green except the .tmp p which would be red, BECAUSE OF SPECIFICITY

In the most general and very broad sense, in terms of specificity, INLINE > ID > CLASS > ELEMENT with INLINE being the most specific and element being the least.

W3Schools Specificity

MDN Specificity

Here is a very interesting Specificity Calculator where you can copy and paste your styles and it will calculate the specificity for you.


Specificity Hierarchy

Every CSS selector has its place in the specificity hierarchy. There are four categories which define the specificity level of a selector:

How to Calculate Specificity?

Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element.

Points Style Specificity
1000 Inline styles - Example: < h1 style="color: pink;">
100 IDs - Example: #navbar
10 Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
1 Elements and pseudo-elements - Example: h1, ::before


Note: Inline style gets a specificity value of 1000, and is always given the highest priority!
Note 2: There is one exception to this rule: if you use the !important rule, it will even override inline styles!

The selector with the highest specificity value will win and take effect!

The table below shows some examples on how to calculate specificity values:

Selector Specificity Value Calculation
p 1 1
p.test 11 1 + 10
p#demo 101 1 + 100
< p style="color: pink;"> 1000 1000
#demo 100 100
.test 10 10
p.test1.test2 21 1 + 10 + 10
#navbar p#demo 201 100 + 1 + 100
* 0 0 (the universal selector is ignored)

The selector with the highest specificity value will win and take effect!

Back to Top