Transferred from: http://www.planabc.net/2008/05/06/css_specificity/
CSS2.1 provides a method for calculating the CSS rules specificity (specificity), using a four-bit number string (Note: The CSS2 is three-bit) to represent, and finally to specificity the high and low to determine the priority of CSS.
Specificity specific calculation rules:
- 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 attribute selector (example [attr= "]), each pseudo-class (example: hover), plus 0,0,1,0.
- Each element or pseudo-element (example: firstchild), etc., plus 0,0,0,1.
- Additional selectors (example global selector *, sub-selector >), plus 0,0,0,0.
Finally, the final specificity value is added to the number string, which is compared to the left-to-right order by bit. That is, compare the size of the numbers.
There are some other rules besides specificity:
- !important declares a rule above all, and if!important declares a conflict, it compares precedence.
- If the priority is the same, then according to the source code in the "later on" principle.
- Style attributes derived from inheritance do not participate in the calculation of specificity, below all other rules (example global selectors *).
Example:
h1 {color:red;} /* Only one normal element is added, the result is 0,0,0,1 */body h1 {color:green;} /* Two ordinary element bonus, the result is 0,0,0,2 *//*0,0,0,1 less than 0,0,0,2, the latter wins */h2.grape {color:purple;} /* An ordinary element, a class selector bonus, the result is 0,0,1,1*/h2 {color:silver;} /* An ordinary element, the result is 0,0,0,1 *//*0,0,1,1 greater than 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 (sub-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 less than 0,1,0,1, which wins */
css--Priority level