One of the more confusing (but important) pieces of CSS is specificity. I have to admit, this concept took me quite a while to grasp. And while it is definitely a bit confusing, once you get the hang of it it’s actually fairly straightforward. With that being said, here is a quick “what and how” on understanding CSS specificity.

The “What”

By rule, the browser will read your CSS file from top to bottom. That means if you have two h1 selectors, the one that occurs lower on the file will be read.

h1 {
   color: red
}
h1 {
   color: orange
}
//Browser will display h1’s in orange since it is lower down

Often times when you are writing CSS, you will have multiple “rules” written into your CSS file that may contradict each other. The way the browser determines how to prioritize those rules is through specificity.

Example: Let’s say you have a to-do list. Each to-do has a class of “to-do”, but some of them have a unique ID (using ID’s isn’t recommended, but they are helpful here in understanding specificity):

//HTML

<div class="to-do"> 
    To-Do #1 
</div>
<div class="to-do" id="second-to-do"> 
    To-Do #2 
</div>
<div class="to-do"> 
    To-Do #3 
</div>

In your stylesheet, you style each element with class “to-do” with a background color of red. However, you also style the element with the id of “second-to-do” with a background color of green:

//stylesheet

.to-do{
   background-color: red
}
#second-to-do{
   background-color: green
}

#styling #css #web-page-design #css-specificity #css-in-js

CSS Specificity: The “What”, The “How”
1.55 GEEK