I found many friends do not know much about the priority of CSS, and the rules are very simple. One thing to note: If your style management needs to deeply judge the priority of CSS, should you reflect on your CSS code? Is it reasonable? Optimized?
CSS2.1 specifies the Specificity (Specificity) calculation method of CSS rules, which is represented by a four-digit numeric string (note: three digits are used in CSS2, finally, the priority of CSS is determined based on Specificity.
Specific Specificity calculation rules:
- Add 1, 0, 0, 0 to the style attribute of the element.
- Select the identifier (# ID) for each id, and add 0, 1, 0, and 0.
- Each class identifier (. class), each attribute identifier (for example, [attr = ""]), and each pseudo class (for example, hover), plus 0, 0, and 1. 0.
- Add 0, 0, 0, and 1 to each element or pseudo element (for example, firstchild.
- Other delimiters (for example, global delimiters *, sub-delimiters>), plus 0, 0, 0.
Finally, the final Specificity value is obtained through the phase-by-phase addition string, which is compared by bit from left to right.
In addition to Specificity, there are other rules:
- ! Important declares more rules than anything else. If! If important declares a conflict, the priority is compared.
- If the priorities are the same, the "post-come" principle in the source code is used.
- The inherited style attributes do not participate in specificity calculation. They are less than all other rules (for example, global selector *).
Sample analysis:
The code is as follows: |
Copy code |
H1 {color: red;}/* only one common element is added. The result is 0, 0, 1 */body h1 {color: green, the result is 0, 0, * // * 0, 0, is less than 0, 0, the latter wins */h2.grape {color: purple ;} /* a common element and a class operator addition result: 0, 0, 1, 1 */h2 {color: silver;}/* a common element with a result of 0, 0, 0, 1 * // * 0, 0, 1, and greater than 0, 0, 1. The former wins */html> body table tr [id = "totals"] td ul> li {color: maroon ;} /* Seven common elements, one attribute selector, and two other selector (sub-selector>). The result is 0, 0, */li # answer {color: navy ;} /* an ID selector and a common selector. The result is, * // *, is smaller than, and. The latter wins */ |