CSS: specificity (selector priority)

By Xah Lee. Date: . Last updated: .

What is specificity?

CSS specificity is a system to determine which CSS selector has priority, when multiple selectors match the same element, when CSS Cascade is a tie.

Example. CSS Rule Conflict

<p id="id8480" class="xclass">good morning</p>
#id8480 {
 color: green;
}

p {
 color: red;
}

.xclass {
 color: blue;
}

Specificity score

Specificity Score is three numbers, written as (a,b,c) . Each number is the count of matches for a specific type of selector.

  1. (1,0,0) for ID selector e.g. #x1722
  2. (0,1,0) for e.g. .nav, [type="text"], :hover
  3. (0,0,1) for e.g. p, div, ::before

Specificity Comparison

left-most number has the highest priority. e.g. 1,0,00,9,0

Example of specificity of common selectors

Selector Specificity Score
#id .x(1,1,0)
#id p(1,0,1)
#id(1,0,0)
p:hover(0,1,1)
p.x(0,1,1)
.x.y(0,2,0)
.x(0,1,0)
p(0,0,1)
::before(0,0,1)
*(0,0,0)

Example of computing specificity

suppose we have

div.x li {
 color: red;
}

Example. Multiple Classes vs ID

/* specificity score (1,0,0) */
#sidebar {
 color: red;
}

/* 
specificity score (0,2,1)
this is a descendant combinator.
its specificity is the sum of its operands
*/
.sidebar .box p {
 color: blue;
}

Specificity of special selectors

Specificity of combinators

for combinators, their specificity is the sum of their operands.

For example div p has specificity of (0,0,2).

Specificity of special selectors: * :where()

The universal selector (*) and complex selector (combinators) is 0.

specificity of :where() is 0.

Specificity of special selectors: :is() :has() :not()

the specificity of :not(arg), :is(arg), :has(arg), is highest specificity of its argument.

CSS rules priority order

CSS. misc, advanced

CSS. Selectors

Selector types
Simple selectors
Combinators
Selector list
Special selector
Misc