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.

LIVE PREVIEW
loading editor…

The first paragraph is targeted by three rules. The id wins because it is the most specific, not because it comes last.

Your turn → Comment out the #special rule. The class takes over. Comment that out too and the element selector is all that is left. That descent is the specificity ladder.

✦ 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.

◈ Graded Build

Style a card component using classes rather than ids. The card needs a class of card, a heading inside it with class card-title colored #B9834F, and a paragraph inside it. Use a descendant selector so the paragraph is only styled inside a card, and give the card a visible border.

Checked against the page you actually render, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back