CSS Specificity

Zephyr
2 min readJan 31, 2022

CSS Specificity is not clean-cut. However, there are methods to explain it in a simple and structured way. Hopefully, this article will help you to become a better and cleaner coder.

Let's start, What is Specificity?

Specificity determines which CSS rule is applied by the browsers. If there are two or more CSS rules that point to the same element, then the selector with the highest specificity value will take effect. Think of it like a scoring system or a ranking hierarchy that determines which style declarations will ultimately be applied to an element.

Specificity is usually the reason why your CSS rules don’t apply to some elements, although you think they should have. There are four categories that define the specificity level of a given selector:

Inline styles
Ex: <h1 style=”color: green;”>

ID
Ex: #section { padding: 10px; }

Classes and pseudo-classes
Ex: a:visited { text-decoration: underline; }

Elements pseudo-elements
Ex: h1, p, :before, :after

There are two things you should understand about specific selectors:

  1. When selectors have an equal specificity value, the latest rule is the one that counts.
  2. When selectors have an unequal specificity value, the more specific rule is the one that counts.

Now, how to calculate specificity for each selector is with pre-set values for each one! Remember that scoring/ranking system we mentioned earlier…

100 for each ID value

10 for each class value or pseudo-class

1 for each element selector or pseudo-element

Inline style is always given the highest priority and gets a specificity value of 1000

Specificity: Basic Principles

ID selectors have a higher specificity than attribute selectors.

Contextual selectors are more specific than a single element selector.

The last rule defined overrides any previous, conflicting rules.

A class selector beats any number of element selectors.

The CSS Specificity is a difficult and frustrating concept to grasp, but with practice, you’ll overcome it in no time. The different weight of selectors is usually the reason why your CSS rules don’t apply to some elements. In order to save yourself some time and stress from combing through all your code just to figure out where you went wrong, having a firm understanding of how specificity works will help you in the long run. Most problems that arise are typically caused by the simple fact that somewhere among your CSS rules… you’ve defined a more specific selector. 😜

--

--