How is specificity calculated when several CSS rules match one element?
Quick answer
Compare each matching selector using three columns: IDs, class-like selectors (classes, attributes, and pseudo-classes), then type selectors and pseudo-elements. The first column where the values differ decides the comparison; a higher value there wins, regardless of later-column totals. Do not judge by selector length. First check that origin, importance, and cascade layers do not already decide the result; specificity applies after those considerations. If specificity ties, later cascade rules, including source order when applicable, resolve the result. [S1]
The question, the details, the next step.
A practical checklist
Confirm both declarations match the element and set the property you are comparing.
Check origin, importance, and cascade layer before specificity.
Count IDs, class-like selectors, and types in separate columns.
Compare from the ID column left to right; stop at the first difference.
If all columns tie, continue through the cascade and check source order when applicable.
A few more useful answers
Do attribute selectors count in the same column as classes?
Yes. Attribute selectors belong in the class-like column, alongside classes and pseudo-classes. [S1]
Does one ID lose to several classes?
Not in the specificity comparison: an ID in the first column outweighs any number in a later column. Check origin, importance, and cascade layer before applying that comparison. [S1]
Does a specificity score by itself prove which rule wins?
No. Specificity is considered after origin, importance, and cascade layers; equal specificity also requires further cascade comparison, including source order when applicable. [S1]
Sources
References used for this guide.
- [S1] Specificity — MDN developer.mozilla.org · Checked
