Class Selectors
A dot followed by a name selects every element carrying that class, classes can be chained for elements that have several, and each class adds one to the middle specificity column.
Match reusable classes, including an element that must carry several classes.
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.