The Cascade, Inheritance, and Specificity
The problem this solves. Two rules both target the same element and set the same property to different values. Only one can win. The browser needs a deterministic way to choose, and that system has three parts.
1. Inheritance. Some properties pass down to descendants automatically, mostly text-related ones like color and font-family. Layout properties like margin do not.
2. Specificity. A more specific selector beats a less specific one.
3. Source order. When specificity ties, the rule written later wins.
How specificity is counted. Think of it as three columns:
ids count in the first column
classes, attributes and pseudo-classes count in the second
element types count in the third
#hero is (1,0,0). .card .title is (0,2,0). nav a is (0,0,2). Compare left to right, and the first column that differs decides it. A single id beats any number of classes, which is exactly why over-using ids makes a stylesheet hard to work with.
✦ About !important
Adding !important to a declaration makes it beat everything regardless of specificity. It exists for genuine emergencies, such as overriding a third-party stylesheet you cannot edit. Reaching for it to fix your own CSS means the real problem is your selectors, and the next override will need !important too. That escalation is how stylesheets become unmaintainable.
Mark this lesson complete
Signed in, your progress follows you to every device.