What is the specificity of CSS selectors

October 8, 2022

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

CSS has many selectors, such as: id, class, when an element is selected by different selectors, the concept of specificity of CSS selectors is very important, the choice with the highest specificity of CSS selectors, the style of the selector will appear first. This article will talk about the detailed specificity of most selectors.

Specificity score

Before learning the specificity of each selector, you need to understand the concept of specificity scoring. Each style composed of selectors will have an aggregate score, and the one with the highest score will be applied. However, when we are writing CSS, we should choose the one with a lower score instead of a higher score; because if there is a more important style in the future, it will be easier to add . If a certain style is written as the most important at the beginning, it will become difficult to add other styles in the future.

Selector score

Selector score

Selector specificity

  • An example of common specificity priority is as follows
!important > inline styles > id > class = pseudo-element > type selector = pseudo-class > generic

In addition to the score calculation, there are a few additional features of style specificity

  • !important scores the heaviest, so please use with care
  • If the specificity is the same, the style that occurs last takes effect
  • If it is through inheritance, the style specificity will be the lowest

Practical examples

Use the following example to understand how the specificity score of selectors is calculated

<a class="my-class another-class" href="#">
  A link
</a>
// 1
a {
  color: red;
}

// 1+10 = 11
a.my-class {
  color: green;
}

// 1+10+10 = 21
a.my-class.another-class {
  color: black;
}

// 1+10+10+10 = 31
a.my-class.another-class[href] {
  color: purple;
}

// 1+10+10+10+10 = 41
a.my-class.another-class[href]:hover {
  color: lightgrey;
}

// From the above score, we can know that the above Link is purple, and when the cursor moves to this element, it will become light gray

source

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee