preface

The weight problem of CSS selectors seems simple, but if something goes wrong, it’s not easy to find the cause. This article specifically introduces CSS selector weights, hoping to help you.

The type of selector

  • ! important
  • Inline style
  • The ID selector
  • The class selector
  • Element selector
  • Wildcard selector

The concept of weights and weights

We can better understand the weight of a selector by adding the concepts of weight and weight level to the selector (note: the concepts of “weight” and “weight level” are proposed to better understand the weight, but do not really exist).

The weight of the selector

With weights and levels in mind, we can refer to tables to understand the weights of elements. The weights of selectors can be added, for example:

Same weight

Because HTML code is executed from top to bottom, subsequent selectors overwrite the same attributes of previous selectors with the same weights:

The weights are different

If both selectors overwrite the same attribute, the selector with the higher weight takes effect.

Ex. :

Weights of transition

Weight transitions discuss the question of which selector style takes effect when there are 11 element selectors and 1 class selectors that simultaneously select the same element. Conclusion: the high-weight selector style will work.

Way of Understanding 1

Because the weights cannot jump, that means that no matter how many level 0 selectors there are, the level 1 selector is still in effect, because the weight level of the selector cannot jump.

Way of Understanding 2

CSS does not use base 10, but base 256, so 10 low-level selectors do not equal one high-level selector

Other selectors

  • Pseudo class selector
  • Property selectors Pseudo-class selectors and property selectors have weights equal to those of class selectors, with a weight level of 2.
  • Pseudo-element selector The pseudo-element selector has a weight equal to the weight of the element selector and has a weight level of 1.
  • Child selector
  • Descendant selectors Children and descendants can be element selectors, class selectors, and ID selectors, so it is a case-by-case analysis.

conclusion

That’s all for this article about CSS selector weights. If there are any incorrect places, please correct them. Please give me a thumbs up if you like