CSS: specificity (selector priority)
What is specificity?
CSS specificity is a system to determine which CSS selector has priority, when style rules clash.
- Multiple selectors match the same element.
- They specify the same property. E.g.
color - Their CSS Cascade origin or layer is a tie.
Example. CSS Rule Conflict
<p id="id8480" class="xclass">what color am i</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,0,0)for ID selector e.g.#x1722(0,1,0)for e.g..nav,[type="text"],:hover(0,0,1)for e.g.p,div,::before
Specificity Comparison
left-most number has the highest priority. e.g. 1,0,0 ≻ 0,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; }
- There are 2 tag name selectors,
divandli, together has specificity (0,0,2) - There is one class selector
.x, it has specificity (0,1,0) - Together, their sum is (0,1,2)
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
combinators
for combinators, their specificity is the sum of their operands.
For example div p has specificity of (0,0,2).
universal selector *
specificity is 0.
:where selector
specificity is 0.
:is :has :not seletors
the specificity of
:not(arg),
:is(arg),
:has(arg),
is highest specificity of its argument.
CSS. Selectors
Selector types
Simple selectors
- CSS: type selector (tag name)
- CSS: universal selector (* any tag)
- CSS: class selector (.x)
- CSS: ID selector (#)
- CSS: attribute selector ([x])
Combinators
- CSS: descendant selector (space)
- CSS: child selector (>)
- CSS: adjacent sibling selector (+)
- CSS: subsequent sibling selector (~)
Selector list
Nesting syntax
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, last child, only child selectors
- CSS: nth-child selector
- CSS: nth-child arg of selector
- CSS: nth-of-type selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: :not negation selector
- CSS: :has descendant selector