Jade McDaniels
2 min readAug 12, 2021

--

color swatches
Photo by Clay Banks on Unsplash

Specificity is the process by which a browser determines what CSS property values to apply to an element in cases where that same element is targeted more than once. Specificity is determined by applied selectors. If an element is selected only once, then specificity isn’t a concern. Understanding specificity makes it easier to debug CSS files as well as efficiently style your HTML. Listed in the order of increasing specificity, selectors are below:

  • type selectors, pseud -elements
  • class selectors, attribute selectors, pseudo-classes
  • ID selectors

What I haven’t listed is the important(!important) rule. The important rule should be used sparingly as it breaks every CSS specificity rule. The important rule overrides all styling rules applied to a specific property. The only way for it to be overridden is to add another !important tag with the same selector later down the file. Another option is to attach the !important tag to a selector with higher specificity.

Here are a few examples of how specificity rules are applied.

div{
background-color:green;
}
div{
background-color:red;
}

Result: In this instance, the targeted element is selected twice. The last declaration is applied so the <div> will appear red.

div{
background-color:red;
}
div.name{
background-color:green;
}

Result: div.name is more specific so the background of the <div> will be green.

div.name{
background-color:green;
}
div#myId{
background-color:red;
}

Result: div#myId is more specific so the <div> appears red.

div#myId{
background-color:red;
}
div.name{
background-color:green !important;
}

Result: Since the important rule overrides all CSS specificity, the <div> appears green in the browser. Again, use the important rule sparingly. Appropriate use cases are if you’re

  • overriding inline styling (inline styling is also something to be avoided)
  • forcing a style regardless of applied CSS styles (sometimes this can be solved through being more specific so check your options)
  • styling foreign CSS
<html>
<body id="parent">
<h1>Here is a title!</h1>
</body>
</html>
#parent {
color: green;
}

h1 {
color: purple;
}

Result: In this case, the <h1> will appear purple. This was confusing initially. At first glance, I thought the <h1> would be green since the id selector has greater specificity. However, it’s purple because the element itself was targeted. Remember, targeted elements always take precedence over inherited elements.

With these rules, you’re set to start styling. It definitely takes some practice to get these rules down (I’m still practicing myself ) but knowing them makes styling effectively a whole lot easier. I hope this helps!

--

--