Andrew's Digital Garden

Specificity in CSS

Specificity is an algorithm that calculates the weight that is applied to a given CSS declaration. The weight is determined by the number of selectors of each weight category in the selector matching the element (or pseudo-element).

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

ID column (x-0-0) Includes only ID selectors.

CLASS column (0-x-0) Class selectors, attribute selectors, and pseudo classes.

TYPE column (0-0-x) Element type selectors and pseudo elements.

Once the specificity values of the relevant selectors are determined, the number of selector components in each column are compared, from left to right. Whichever selector has a higher value in the most left column wins. e.g. 1-0-0 beats 0-4-0.

If the competing selectors have the same values in all the three columns, the proximity rule comes into play, wherein the last declared style gets precedence. Given an element that has two classes:

<div class="rule1 rule2">Content</div>

The CSS applied to the element wold be which class is defined last in the stylesheet.

.rule2 { background-color: green; } .rule1 { background-color: red; }

In this case, rule1 styling would apply.

[[css]]

Referred in

Specificity in CSS