TechnicalMedium HTML & CSS

How does CSS specificity work?

Asked for Frontend Developer

Why they ask this: Explains "why is my style not applying?" problems that every frontend developer hits.

Answer

When several rules target the same element, the browser picks the one with the highest specificity. If specificity is equal, the rule that appears later wins.

Specificity is compared as (IDs, classes/attributes/pseudo-classes, elements/pseudo-elements):

SelectorSpecificity
p(0, 0, 1)
.card p(0, 1, 1)
#main .card p(1, 1, 1)
inline style=""beats any selector
!importantoverrides normal declarations; avoid it

:where() adds zero specificity, while :is() and :not() take the specificity of their most specific argument.

Keep specificity low and flat (for example single classes with a BEM-style or utility approach) so styles stay easy to override.

Can you explain this in your own words?

Back to question bank