CSS Specificity

CSS Specificity

·

2 min read

Before jumping into the topic, let's see an example.

Can you guess the color of the paragraph?

/* CSS */
p{ color: green;}
p{ color: red;}
<!-- HTML -->
<p class="msg" id="intro">
  Welcome to CSS specificity tutorial.
</p>

If you said RED, yes it's correct. The browser has to pickup only one color from Green and Red. The later one takes priority. This is one of the CSS fundamental rules.

We see CSS rules Priority/Specificity more in detail.

If you are new to CSS Selectors, please refer to my previous blog post on CSS Selectors

Let's see a complex example.

/* CSS */
p{ color: blue;}
.msg{ color: red;}
#intro{ color: green;}
<!-- HTML -->
<p class="msg" id="intro">
  Welcome to CSS specificity tutorial.
</p>

Now tell me the color of the paragraph? Here, we have used tag, class and id selectors to specify the colors.

The color is green because id selector takes precedence over tag and class selectors.

CSS Specificity:

Thumb Rule

Remember how to calculate priority/specificity. Here is the Thumb Rule.

  • Tag/element - 1
  • Class - 10
  • Id - 100
  • Style attribute - 1000

Now, let us apply these rules to the above example.

In our example we have tag (p), class (msg) and id (intro). As per the rule Id takes precedence, so the Id style is applied which is color green.

Explanation of the Specificity

The #intro{ color: green;} rule is more specific than the others because ids must be unique throughout a web page and can thus only target one element.

.msg{ color: red;} can target any HTML element with a class="msg" attribute and is consequently less specific. Same goes for p{ color: blue;} which can target any HTML paragraph.

Here is a more complex example.

CSS_Priorities.png In the above screen 1, 2,...5 shows the priority/specificity.

Hope it helps!