What is CSS selector specificity and how does it work?

CSS selector specificity is a system used by web browsers to determine which CSS styles should be applied to an element on a web page. It is based on the concept of specificity, which is a value assigned to a CSS selector based on the number and type of selectors used in the rule.

The specificity value of a selector is calculated by assigning a point value to each part of the selector:

  • A type selector (e.g. div) or universal selector (*) is assigned a value of 0,0,0,1
  • A class selector (e.g. .my-class), attribute selector (e.g. [type=button]), or pseudo-class (e.g. :hover) is assigned a value of 0,0,1,0
  • An ID selector (e.g. #my-id) is assigned a value of 0,1,0,0
  • An inline style (e.g. style attribute on an HTML element) is assigned a value of 1,0,0,0

When the browser encounters multiple CSS rules that could apply to a given element, it compares the specificity values of the selectors to determine which rule should be applied. The rule with the highest specificity value wins.

Here is an example:

/* specificity value: 0,0,0,1 */
div {
  background-color: blue;
}

/* specificity value: 0,1,0,0 */
#my-id {
  background-color: red;
}

In this example, the element with the ID of "my-id" will have a red background color, because the ID selector has a higher specificity value than the type selector.

CSS also allows to override a rule with the !important keyword, which will make a rule more specific than any other rule.

In summary, CSS selector specificity is a system used to determine which CSS styles should be applied to an element on a web page. Specificity is a value assigned to a CSS selector based on the number and type of selectors used in the rule, and when the browser encounters multiple CSS rules that could apply to a given element, it compares the specificity values of the selectors to determine which rule should be applied. The rule with the highest specificity value wins.

Continue Reading