May 29, 2021 Article blog
CSS selectors are mandatory, and multiple selectors have their own usage, and this article introduces you to the priorities of selectors.
We can divide the priority of CSS from highest to lowest into six levels:
Level 1: Properties without priority we just need to add
!important
after the property.
This property can override the same element style defined at all locations on this page.
Second level: Add style directly within the element label, commonly known as inline style.
Level 3: ID selector. E xample: #id(color:red); }
Level 4: Class selector, property selector, or pseudo-class selector. E xample: .one(color:blue); }
Level 5: Element selector. E xample: div(color:yellow); }
Level 6: All-in-one selectors. E xample: s.color:green; }
CSS prioritizes the style weights it defines based on the special nature of the selector, with the more specific selector weights taking precedence over the general selector rules. If you have two selectors with the same particularity, the selectors defined later take precedence.
How do I calculate the particularity of a selector? Let's try to calculate the weight of the selector, as shown below:
As shown in the figure, we divide the selector specificity into four levels, each of which is a selector, and the value of each level adds up to the weight of the selector.
The four levels are defined as follows:
Level 1: Inline style, e.g. style," which has a weight of 1000
Level 2: ID selector, example: #id, its weight is 100
Level 3: class selector, example: .one, which has a weight of 10
Level 4: Element selector, example: div, p, h1, with a weight of 1
The above is for everyone to organize the CSS selector weight priority rules.