Quiz

What is CSS selector specificity and how does it work?

Topics
CSS
Edit on GitHub

When multiple CSS rules could apply to the same HTML element, the browser needs a way to decide which rule takes precedence. This is determined by the CSS cascade, which considers importance, inline styles, selector specificity, and source order. Selector specificity is a key part of this process, calculating a weight for each selector.

The browser determines what styles to show on an element depending on the specificity of the CSS rules that match it. Specificity is calculated for each rule to decide which one takes precedence.

How is specificity computed?

The specificity algorithm is basically a three-column value of three categories or weights - ID, CLASS, and TYPE - corresponding to the three types of selectors. The value represents the count of selector components in each weight category and is written as ID - CLASS - TYPE. The three columns are created by counting the number of selector components for each selector weight category in the selectors that match the element.

  1. ID: This is the count of ID selectors (e.g., #example).
  2. CLASS: This is the count of class selectors (e.g., .my-class), attribute selectors (e.g., [type="radio"]), and pseudo-classes (e.g., :hover).
  3. TYPE: This is the count of type selectors (element names, e.g., h1, div) and pseudo-elements (e.g., ::before).

When comparing selectors to determine which has the highest specificity, look from left to right (ID, then CLASS, then TYPE), and compare the highest value in each column. A value in the ID column will override values in the CLASS and TYPE columns, no matter how large they are. Similarly, a value in the CLASS column overrides any value in the TYPE column. For example, a specificity of 1,0,0 (one ID) is greater than 0,10,10 (ten classes and ten types).

It's important to remember that specificity is part of the broader CSS cascade. Declarations marked !important have the highest precedence, followed by inline styles (using the style attribute). Selector specificity comes next.

In cases of equal specificity among competing rules (that aren't inline or !important), the rule that appears last in the CSS source order is the one that counts and will be applied.

It's a better practice to write CSS rules with low specificity so that they can be easily overridden if necessary. When writing CSS for UI component libraries, it is important that styles have low specificities so that users of the library can customize them without needing overly complex selectors or resorting to !important.

References

Edit on GitHub