The priority issue is actually a conflict resolution issue. When the same element (or content) is selected by a CSS selector, different CSS rules must be chosen according to priority. There are actually many issues involved.
The first is the specificity of CSS rules. CSS2.1 has a set of calculation methods for specificity, which is represented by a four-digit number string (CSS2 is three-digit). In the end, the higher the specificity, the more special the rule. In the priority It will be more advantageous when making judgments. Regarding the specific calculation of specificity, there are the following general rules for numerical addition in various situations:
for each ID selector (#someid), add 0,1,0,0.
Each class selector (.someclass), each attribute selector (formed like [attr=""], etc.), each pseudo-class (formed like: hover, etc.) add 0, 0, 1, 0
to each element or Pseudo elements (:firstchild), etc., add 0,0,0,1
. Other selectors include the global selector *, add 0,0,0,0. It is equivalent to not adding it, but this is also a kind of specificity, which will be explained later.
According to these rules, the number strings are added bit by bit to get the final calculated specificity, and then compared bit by bit in order from left to right when comparing and choosing.
Let’s give some examples:
h1 {color: red;}
/* There is only one ordinary element bonus, the result is 0,0,0,1 */
body h1 {color: green;}
/* Add two ordinary elements, the result is 0,0,0,2 */
--The latter wins
h2.grape {color: purple;}
/* An ordinary element and a class selector are added, and the result is 0,0,1,1*/
h2 {color: silver;}
/*An ordinary element, the result is 0,0,0,1 */
--The former wins
html > body table tr[id="totals"] td ul > li {color: maroon;}
/* 7 ordinary elements, one attribute selector, two other selectors, the result is 0,0,1,7 */
li#answer {color: navy;}
/* An ID selector, a normal selector, the result is 0,1,0,1 */
--The latter wins
In addition to specificity, there are some other
style styles within the rule text that have a priority of 1,0,0,0, so they are always higher than external definitions. Here, in-text styles refer to styles that look like