CSS specificity (source code)

= CSS specificity
{c}
{title2=$(A,B,C)$}

<CSS specificity> ranks selectors by their components when the <CSS cascade> reaches its specificity comparison. In the <Selectors Level 4 by World Wide Web Consortium> convention, the triple $(A,B,C)$ counts ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors respectively. The comparison uses <lexicographic order>: compare $A$ first, then $B$ if needed, then $C$.<Selectors Level 4 by World Wide Web Consortium>[§17, Calculating a selector's specificity]{ref}

For example, `p.warning` has specificity $(0,1,1)$, `.warning.urgent` has $(0,2,0)$ and `#notice` has $(1,0,0)$. The ID selector outranks either class-based selector at this stage. The triple is not a base-ten number: sufficiently many classes do not carry into the ID component. A descendant <CSS combinator> such as the space in `article p` contributes no count of its own.

Some functional <CSS pseudo-classes> have explicit exceptions. `:where(#notice)` contributes zero specificity, while `:is(.warning, #notice)` takes the maximum specificity of its argument list, here $(1,0,0)$. This is not necessarily the specificity of whichever individual alternative happened to match.<Selectors Level 4 by World Wide Web Consortium>[§17, special specificity rules for :is(), :not(), :has() and :where()]{ref}

Specificity is not the whole priority system. Origin, importance and <CSS cascade layers> can decide before selector counts are compared; later source order can decide a remaining tie. Consequently, an author can override a highly specific normal declaration with a lower-specificity important declaration in the appropriate cascade context.<CSS Cascading and Inheritance Level 5 by World Wide Web Consortium>[Cascade Sorting Order, origin/importance, layers, specificity and order of appearance]{ref}