Detailed |CSS Priority
Found that a lot of friends do not know the priority of CSS, the rules are simple. Need to explain the point, if your style management needs to deeply judge the priority of CSS, more should reflect on their own CSS code, is it reasonable? Is it optimized?
The CSS2.1 rules on the specificity (specificity) of the CSS rule, using a four-digit string (note: CSS2 in the three-bit), and finally to specificity to judge the priority of the CSS.
Specificity specific rules of calculation:
- The style style property of the element, plus 1,0,0,0.
- Each ID selector (#id), plus 0,1,0,0.
- Each class selector (. Class), each property selector (example [attr= "]), each pseudo class (example: hover), plus 0,0,1,0.
- Each element or pseudo element (example: FirstChild), plus 0,0,0,1.
- Other selectors (example global selector *, sub-selector >), plus 0,0,0,0.
The final specificity value is obtained by adding a digit string at the end, and is compared sequentially from left to right.
In addition to specificity there are some other rules:
- The rules of the!important declaration are above all, and if the!important declares a conflict, then the precedence is compared.
- If the priority is the same, then according to the source code in the "later on" principle.
- The style attributes obtained by inheritance do not participate in specificity calculations, and are below all other rules (example global selector *).
Example Analysis :
h1 {color:red;}
/* Only one common element addition, the result is 0,0,0,1 * *
Body h1 {Color:green;}
* * Two common element addition, the result is 0,0,0,2 * *
/*0,0,0,1 is less than 0,0,0,2, the latter wins
H2.grape {color:purple;}
/* A common element, a class selector Plus, the result is 0,0,1,1*/
h2 {Color:silver;}
/* A common element, the result is 0,0,0,1 * *
/*0,0,1,1 is greater than 0,0,0,1, the former wins
HTML > Body table tr[id= "totals"] td ul > li {color:maroon;}
/* 7 ordinary elements, one property selector, two other selectors (Child selector >), the result is 0,0,1,7 * *
li#answer {color:navy;}
/* An ID selector, a normal selector, the result is 0,1,0,1 * *
/*0,0,1,7 is less than 0,1,0,1, the latter wins
Excerpt OLD9 's "CSS priority" (Cannot traverse GFW)