Class Selectors
The special dish needs a golden border, but only the special one. Element selectors cannot tell one article from another. Classes can, and that is why they are the everyday workhorse of CSS.
The rule
A dot means class:
.namepicks every element wearing that label.
.dish {
padding: 1rem;
}
.special {
border: 2px solid goldenrod;
}Every example uses the Harbour Café page from the first lesson of the course: a header with an h1 and a nav of two links, a section#menu holding an h2 and two article.dish cards (the second is also .special), each with an h3, a p.price and a description p, then a section#visit with an h2 and one p, and a footer with one p.
.dish matches both articles. .special matches only the lassi's article. Because an element can wear several classes, the lassi gets the padding and the border.
Classes combine in useful ways:
- Two classes glued together,
.dish.special, means "an element that has both". No space. - Element plus class,
p.price, means "apthat has classprice". - With a space,
.dish .special, means something different: an element with classspecialthat sits inside a.dish. You will meet that in the next section.
Class names are case-sensitive: .Price does not match class="price".
Each class adds (0,1,0) to specificity. So .dish.special is (0,2,0), and p.price is (0,1,1). One class outranks any number of element names.
The shortcut
Read dots as "has the label", and read the gap. No gap means "the same element has all of these"; a space means "something inside".
Find it
The lassi's
h3sits inside<article class="dish special">.
Drills
Answer fast — trust the rule.
How many elements does .dish.special match on the café page?
How many elements does .dish .special (with a space) match on the café page?
Does .Price match <p class="price">?
What is the specificity of p.price?
Remember
.nameselects every element carrying that class.- No gap means "same element has all"; a space means "inside".
- A class is worth (0,1,0) and names are case-sensitive.
