Specificity and source order
Definition and purpose
Specificity compares matching selectors at the appropriate cascade stage. Count IDs, then classes/attributes/pseudo-classes, then types/pseudo-elements as a tuple. Compare from left to right, not as a decimal number.
ID versus class
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>#a { color: navy; } .note { color: green; }</style> </head> <body> <p id="a" class="note">First</p> <p id="b" class="note">Second</p> </body></html>The ID wins on a; the class still applies to b.
Syntax and mental model
#notice is (1,0,0), .card p is (0,1,1), and p is (0,0,1). Universal selectors and combinators contribute zero. With equal origin, importance, layer and other precedence stages, greater specificity wins; if those and specificity tie, later source order wins. Functional pseudo-classes have special rules studied later.
Equal specificity
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>.first { color: navy; } .second { color: green; }</style> </head> <body> <p id="a" class="first second">Both</p> <p id="b" class="first">First</p> </body></html>The second class wins only where both selectors match.
Common mistakes
Do not add IDs just to win a styling conflict. Inspect the matched declarations first. A late low-specificity rule cannot defeat an earlier high-specificity rule merely by appearing later.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Origins and competing rules. Next lesson: Inheritance and defaulting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Specificity and source order — knowledge check
Five questions on specificity and source order.
What is the specificity of #a .note p?
Which selector has higher specificity?
When does source order settle a conflict in this simplified setup?
What does the child combinator contribute?
Why inspect matched rules before adding an ID?