5月28日 03:23

How CSS Selector Specificity is Calculated

In CSS (Cascading Style Sheets), the specificity of a selector determines its priority. Rules with higher specificity override those with lower specificity. The method for calculating specificity is as follows:

  1. Inline Styles: Styles defined directly within HTML elements using the style attribute. For example, <div style="color: red;"> has a specificity of 1000.

  2. ID Selectors: Such as #content (specificity of 0100).

  3. Class Selectors, Attribute Selectors, and Pseudo-classes: Such as .class, [type="text"], and :hover (specificity of 0010).

  4. Element Selectors and Pseudo-elements: Such as div, p, and ::before (specificity of 0001).

  5. Special Selectors: Combinators such as *, +, >, and ~ do not contribute to specificity.

  6. The !important declaration has the highest specificity and is placed after the style property value, e.g., color: red !important;.

When calculating specificity, the counts for each selector type are computed independently. When comparing specificity, it is evaluated level by level across four digits, with higher specificity rules taking precedence. For instance, selectors with higher specificity override those with lower specificity. Thus, #id p (with specificity 0101) overrides .class .class .class (with specificity 0030). This can be understood as four decimal digits, with the leftmost digit having the highest weight.

Note: Specificity is only one factor in resolving CSS style conflicts; the order of source code and inheritance should also be considered.

标签:CSS