CSS selector priority
Refer to the article
Refer to the article
I. What is priority?
-
The priority is a weight assigned to the specified CSS declaration, determined by the value of each selector type in the matched selector.
-
The browser uses priority to determine which attribute values are most relevant to an element and then applies them to that element. Priority is a matching rule based on different kinds of selectors.
How is the priority calculated?
-
Priorities only make sense when there are multiple declarations for the same element. Because every CSS rule that directly applies to an element always takes over rules that the element inherits from its ancestors.
-
The priority is determined by the values of A, B, C, and D, where their values are calculated as follows:
- If inline styles exist, then
A = 1
, otherwise,A = 0
; B
The value is equal to theThe ID selector
The number of occurrences;C
The value is equal to theClass selectors
和Property selector
和pseudo-classes
The total number of occurrences;D
The value is equal to theLabel selector
和Pseudo elements
The total number of occurrences.
- If inline styles exist, then
-
The rules of comparison are: compare from left to right, the larger one wins, if equal, move one more place to the right for comparison. If all four bits are equal, the last one overwrites the first
-
#nav-list .item { color: #f00; } .nav-list .item { color: #0f0; } (0,1,1,0) > (0,0,2,0)Copy the code
Special circumstances
-
When using a! The important rule overrides any other declarations.
-
! Important has nothing to do with priority, but it is directly related to the end result.
-
Use! Important is a bad habit and should be avoided because it breaks the inherent cascading rules in stylesheets and makes debugging to find bugs more difficult.
-
When two conflicting bands! When the declaration of the important rule is applied to the same element, the declaration with a higher priority will be adopted.
-
Some rules of thumb:
- A certainPrioritize using style rules to solve problems rather than
! important
- onlyUse in specific pages where you need to override site-wide or external CSS
! important
- Don’t everUse it in your plugin
! important
- Don’t everUsed in site-wide CSS code
! important
- A certainPrioritize using style rules to solve problems rather than