Kaigai Blog living abroad in my twenties

【My Study Note】All selectors and their specificity

CSS Programming

All selectors and their specificity


CSS has a set of rules that it uses to ‘score’ or assign a certain weight to selectors and this creates a specificity hierarchy. Based on the weights, there are four categories in this hierarchy.

  1. Inline styles
  2. IDs
  3. Classes, attributes, and pseudo-classes
  4. Elements and pseudo-elements

Inline styles

<!-- In this case, the p tag will be colored white because it is declared inside the inline tag -->
 <p style=“color: white;”> 
p{color: blue} 

Inline styles are attached to the elements within your HTML code like with the ‘style’ attribute. inline styles have the highest specificity. That means that rules that are defined as inline styles will be applied irrespective of other rules.

IDs

#div

Classes, attributes, and pseudo-classes

.my-class 
p[“attribute”]
div:hover

Calculating scores

CSS uses the hierarchical model internally to calculate the specificity of the selectors used on a web page. But often as the size of CSS code increases, developers unavoidably face rule conflicts. In these cases, developers use the specificity hierarchy to calculate the precedence of CSS rules and to control the outcome of their web pages.

For example

  • #hello {} will be 0100
  • div {} will be 0001 and
  • div p.foo {} will be 0012

In the order stated above, the four categories will be assigned values 1000, 100, 10 and 1 with the element selectors having the lowest value of 1. These scores will be calculated respectively for each element present inside the selector. The total score for these elements is then calculated and the one with the highest value has the highest specificity.

Additional Rules

  • Every selector will have a score and place in the hierarchy
  • In the case of selectors with equal specificity, the latest or last written rule is the one that will be applied
  • In general, ID selector should be applied in cases where you need to be certain about a rule
  • Universal selectors (This means “*”) have zero specificity value