Unit 3 · CSS: the look and the layout
ID vs class specificity in CSS
An id selector beats any number of classes: a hundred classes still lose to one #intro. Classes beat element selectors, and several classes together beat one.
The mix-up
What people often think
“A class and an id are about equally strong.”
What the tutor says
An id beats any number of classes. A hundred classes still lose to one #intro.
How it works
Think of specificity as three columns: ids, classes, elements. Compare the left column first; only if it ties do you look at the next. #intro scores 1-0-0, .card .title scores 0-2-0, body p scores 0-0-2.
That is why many teams avoid ids for styling: once an id rule exists, only another id or !important can override it. Classes let you choose which elements get a look, while an element selector like button styles every button on the site.
An example
#intro { color: green; } /* 1-0-0 */
.lead.note { color: blue; } /* 0-2-0 */
p { color: black; } /* 0-0-1 */Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Any class rule ties with any other class rule.”
Classes add up. .btn.primary has two, so it beats .primary, which has one.
“Styling button is the same as styling .btn.”
A button selector styles every button on the site, including ones you have not made yet. A class lets you choose which ones get the look.
Practise it with a tutor watching
The cascade and specificity
Predict which CSS rule wins when several target the same element, and fix fights without !important.
Free, no account needed.