CSS selectors - Who gets priority?

I always wondered how CSS selectors get priority. I knew it was classes above element selectors but was never very sure about the rest until recently when I did a CSS Fundamentals course by Kevin Powell on Scrimba.

It might sound strange but I was not aware of the term specificity until this moment. A term I'm not sure I can pronounce.

Specificity bascically is the answer to my CSS selectors prioritisation question. Before we get into that here is a more official definition:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. *source.

In order words specificity is the way CSS styling will be prioritized based on the CSS selectors defined.

So how does CSS priority or otherwise said CSS specificity work? Here you can see the CSS selectors from lowest priority to the highest priority (specificity):

  • tag selectors like for example an h1 or p tag are worth 1
  • .class selectors are worth 10
  • #id selectors are worth 100

To better illustrate this let’s look at the following example.


 <h1 class="title" id="title">Hello, world!</h1>
 
 
  h1 {
      color: red;
  }

  .title {
      color: green;
  }

  #title {
      color: pink;
  }
 

This will output a pink title as its id selector has the highest priority.

 
 

Hello, world!

It's important to note that the selector with the highest priority will prevail. The order in which the CSS rules appear won't matter. I want to also add that I would never name a class the same way as an id. This specific case where I used class="title" id="title" is only intended to highlight the specificity better.

To add to this, if you would have repeaded something in your stylesheet like for example:

 
  h1 {
      color: red;
  }
  h1 {
      color: green;
  }
  h1 {
      color: pink;
  }
 

Know that the last one defined will be the lucky winner in case they are all having the same priority(specificity).

Summary:

  • #title{ color: pink;} is the most specific one as ids must be unique throughout a webpage, and should only target one element.
  • .title{ color: green;} one the other hand can target any HTML element with a class="title" attribute, and is, therefore, less specific that and id selector.
  • Consequentaly h1 {color: red;} is the least specific as it can target any HTML header 1 tag.

To end I will add that the inline style has a higher priority than the style defined in the internal or external style sheet and by using !important you can override other selectors but I've read that it's not a good practice. I will let you dig more into that on your own as I will myself.


Get in touch!

"It is not because things are difficult that we do not dare, it is because we do not dare that they are difficult."
- Séneca