Specificity

Which selector is more specific? 9 Pt1. Language Specificity Classes are more specific than tags . Because you add classes to mark specific tags. IDs are more specific than classes . Because IDs are supposed to be unique. Adding stuff to a selector makes it more specific. Both .foo .bar , .bar.goo are more specific than .bar Calculating specificity 0. Ignore combinators. 1. More IDs => more specific. 2. More classes => more specific. Pseudo-classes and attributes are counted too. 3. More tags => more specific. Pseudo-elements are counted too. * div .foo div .foo .foo > div #bar :hover a [href] ::after #bar #zoo ID = 0 CLASS = 0 TAG = 0 ID = 0 CLASS = 0 TAG = 1 ID = 0 CLASS = 1 TAG = 0 ID = 0 CLASS = 1 TAG = 1 ID = 0 CLASS = 1 TAG = 1 ID = 1 CLASS = 2 TAG = 2 ID = 2 CLASS = 0 TAG = 0 Order of comparison more general more specific Small rules that fulfills the points. intuitive not so intuitive Logical selectors are special cases :is( S1 , S2 , ...) :not( S1 , S2 , ...) :has( S1 , S2 , ...) The most specific argument is added to the specificity. ID = 0 CLASS = 2 TAG = 0 ID = 0 CLASS = 2 TAG = 1 ID = 1 CLASS = 1 TAG = 0 .bar :is ( .foo , div) .bar :not (.foo, p .bar ) .bar :has (.foo, #goo ) .bar :where (.foo, div) ID = 0 CLASS = 1 TAG = 0 :where behaves like :is without adding any specificity. :where( S1 , S2 , ...) actually not pseudo-classes Hack : repeat to increase specificity .foo.foo.foo #bar#bar#bar ID = 0 CLASS = 3 TAG = 0 ID = 3 CLASS = 0 TAG = 0 Order of importance 10 Pt1. Language Specificity <style> p { color: white; } p { color: black; } .foo { color: blue !important ; } </style> <p>black</p> <p style ="color: red ;"> red </p> <p class="foo" style ="color: red;"> blue </p> <p class="foo" style ="color: red !important ;"> red </p> !important rules CSS in attribute !important & inlined same specificity; last rule wins ID, class, tag last rule wins order of comparison Control priorities with layers @layer base , overrides ; @layer base { /* more specific selectors */ a:link, a:visited { color: blue ; } } @layer overrides { /* less specific, but higher */ a { color: green ; } } a { color: red ; } /* un-layered rules */ a:visited { color: revert-layer ; } low high alternative to !important and hacks which rule wins? topmost higher lower priority list <a href="/visited-link"> green </a> <a href="/not-visited"> red </a> revert to the previous layer (cascade is scoped by layers) Caveat : !important will reverse the order of layers! !important low !important high higher layer lower layer order specificity attribute? !important