Learn CSS intuitively - Specificity

Hey there! Welcome to our new series of posts where we try to decipher CSS concepts in an intuitive manner - by relating those concepts to something you already know in the real world so that we can learn CSS like never before! Are you ready for the first concept?? Let's go! 🚀

Today we look at CSS Specificity. When there are more than one rules in CSS that apply to an element, browser picks the rule whose CSS selector has more “specificity”. But what is this Specificity?

Think of CSS specificity as a hierarchy, where each selector type (eg. ID, class, element selector etc) in the hierarchy has a certain weight or importance.

Let's use the example of a chef's uniform to understand this hierarchy. The uniform has several components, including a hat, apron, shirt. Each component has a different level of specificity, just like each CSS selector type has a different level of specificity/priority.

  • The Hat is the most specific component of the uniform, as it is unique and distinguishes the chef from other kitchen staff. Similarly, an ID selector in CSS is the most specific, as it targets a specific element on the page. In CSS, ID selector has a specificity score of 100.

    #hat_id {
    color: red;
    }
  • The Apron is still specific, but not as much as the hat, as it is worn by all kitchen staff but still distinguishes them from others in the restaurant. Similarly, a class selector in CSS is still specific, but not as much as an ID selector, as it targets a group of elements with a shared class. Class selector has a specificity score of 10.

    .apron_class {
    color: red;
    }
  • The Shirt is the least specific components of the uniform, as they are worn by all kitchen staff and do not distinguish one chef from another. Similarly, element selectors in CSS are the least specific, as they target all elements of a certain type (e.g. all paragraphs).

    p {
    color: red;
    }

So, when a browser is applying styles to an element, it checks the specificity of each CSS selector and applies the style from the most specific selector. If there is a tie, the browser applies the style from the selector that appears last in the stylesheet.

One other thing - Selectors in CSS can be made of multiple selector types too. Eg. the following rule has a selector made up of an ID and a class:

#hat_id .apron_class { 
color: red;
}

In this case, the specificity score of the selector #hat_id .apron_class is the sum of the specificity scores of individual selector types in it i.e. #hat_id (100) + .apron_class (1) = 101

Make sure you understand CSS selector specificity well to keep your stylesheets manageable! You can hop over to CSSBattle and solve some targets to practice CSS Specificity.

How did you like this post? What next concept would you want us to give a shot at?

Let us know on our forum or on the Twitter post.

Want to write for CSSBattle? Mail us your pitch.