Welcome to the new Web Developer's Journal built with Nuxt Content!

CSS Specificity Explained in Simple Terms

To make our life easier, the designers of CSS created multiple levels of specificity depending on the selector. The three main kinds of selectors are:

  • element
  • class
  • id

There are also combinations of the above and pseudo elements and classes.

The traditional way of measuring specificity is to assign number values. Element selectors have a specificity of 1, classes 10, and ids 100. This isn't really the case, because a class will be more specific then a combined selector with any number of elements.

This is more specific:

.list {
  color: #ccc;

Than this:

body main section div div div div div div div ul {
  color: red;

The least specific in the list is element, the most specific is id. Element selectors select html elements without giving them classnames or ids. Classes are more specific, but one class can still apply to multiple elements depending on where you are applying it. From one id, you can have only one instance, and that is the most specific of the three.

In case you have multiple selectors with the same specificity, the last one will overwrite the others. That's cascading in action.

Specificity Best Practices

CSS seems simple at first, but as many discovered, with big project it can quickly become a hard to maintain monster. That's why methodologies like BEM (Block Element Modifier) were created.

You should put general rules on element selectors like body, headings, paragraphs. Everything else should be selected with classes. It's a generally accepted rule not to use id unless you absolutely must. It creates a high specificity that you won't be able to overwrite later, hence you will have a hard time with maintenance.

Compound Selectors

If you follow some of the modern methodologies like the above mentioned BEM, you won't use compound selectors much. Sometimes they do come up, so it's important to understand how they affect specificity.

In the above example, there is a compound element selector. The specificity adds up, so it's 11. Likewise, a selector like .list .item will have a specificity of 20.