Specificity in CSS

Tram Ho

1. What is specificity?

Specificity (or precedence) is how the browser decides which css property to apply to an element when there are multiple css rules pointing to that element. Specificity based on matching rules includes different types of CSS selectors.

2. The hierarchy of specificity

Each selector has its place in the hierarchy. Selector specificity has 4 levels (as shown):

3. How to calculate specificity?

We represent the specificity of a selector as follows:

  • 1-0-0-0: Inline styles
  • 0-X-0-0: Number of ID selector
  • 0-0-Y-0: Number of classes, attributes and pseudo-classes
  • 0-0-0-Z: Number of Elements and pseudo-elements Consider the following example:
SelectorThousandsHundredsTensOnesTotal specificity
h1 + p :: first-letter00030003
li> a [href * = “jav”]> .active00220022
Attributes are written in style attributesfirst0001000

There is a slight confusion often seen when following this table. Consider the following case:

The result is blue. Because the class nature is only specific in the hundreds (X-0-0). No matter how many classes are nested, it will only work for selectors of equal or lower specificity.


  • Universal selector (*) and combinators selector (+,>, ~) do not increase specificity.
  • : not (x): Negation selector (: not) has no value, the new (x) argument increases specificity.
  • Don’t overdo inline styles and! Important, love yourself later!

4. Summary

Specificity with selectors is one of the most important issues in css. Knowing this will help us easily develop and maintain the application.



Share the news now

Source : Viblo