Mathematics of Conflicts
Specificity is not magic, but a strict mathematical formula. Browser adds up weights of all parts of your selector to decide which style to apply.
Point System (Scale 0,0,0)
Let's imagine specificity as three columns: [ID, CLASSES, TAGS].
- Tags and pseudo-elements (
p,::before) = [0, 0, 1]. - Classes, pseudo-classes, and attributes (
.box,:hover,[type]) = [0, 1, 0]. - IDs (
#root) = [1, 0, 0]. - Inline styles — stand above the entire system (technically this is [1, 0, 0, 0]).
Calculation Example:
header nav ul li a: 5 tags = [0, 0, 5]..nav-list .nav-link: 2 classes = [0, 2, 0].- WHO WINS? The second! 20 points (in second column) is always greater than any sum in the third column.
Important
Even if you write 100 tags in a row (div div div...), they will NEVER beat a single class .box.
How to Cure Conflicts?
- Don't use IDs for styles (they're too heavy).
- Don't use !important (it breaks code navigation).
- Change specificity: Want to override a style? Add another class to selector (
.parent .child) instead of shooting sparrows with!important.