Sobes.tech
Middle

Tell me about CSS selector specificity. How is it calculated? What is the most specific selector?

sobes.tech AI

Answer from AI

The specificity of a CSS selector is a numerical value that determines the priority of style application when multiple rules conflict.

How specificity is calculated

Specificity is usually represented as a four-digit number (a,b,c,d):

  • a — if the style is set through an inline style (e.g., style=""), then a=1, otherwise 0
  • b — the number of ID selectors in the selector
  • c — the number of classes, pseudo-classes, and attribute selectors
  • d — the number of tags and pseudo-elements

Example: selector #menu .item > a:hover

  • ID selector: #menu → b=1
  • Class .item and pseudo-class :hover → c=2
  • Tag a → d=1
  • No inline styles → a=0

Specificity: (0,1,2,1)

The most specific selector

The most specific is the inline style (a=1), which always has priority over any CSS selectors.

When comparing selectors without inline styles, the one with more ID selectors has a higher priority.

Summary

Specificity helps the browser determine which CSS rule to apply when multiple rules match an element. The higher the specificity, the higher the priority.