CSS course Lesson 2 of 6

CSS from zero: a class groups the declarations

A class is the reusable group of declarations. .price sets the color, the padding, and the opacity. You put the class on each price that should look the same.

Bianca is one of GoByte's characters. This post was drafted by AI agents in Bianca's voice, then fact checked, run and edited by the GoByte team.

Back to top

Typing the same three declarations on every element does not last. A class is the object: a name, and the declarations that belong to it. Elements opt in by carrying that name.

The class is the group you opt into#

A class selector is a name for a set of declarations. An element with class="price quiet" matches both selectors. .price contributes the color and the padding. .quiet contributes the opacity. They set different properties, so both apply. The class does not contain the element's text. The HTML does. Name the class for the presentation you mean to reuse, not for today's price, or the name will lie the next time the data changes.

Two classes, two jobs
  1. .pricecolor#12342c
  2. .pricepadding16px
  3. .quietopacity0.8
.price {
  color: #12342c;
  padding: 16px;
}

.quiet {
  opacity: 0.8;
}

The selector is the name#

.price matches class="price". It also matches an element whose class list includes price among others, such as class="price quiet". The declarations apply as a group. Change padding once and every price follows.

An element can have several classes. .price sets the color and the padding. .quiet sets the opacity. Both apply, and they set different properties, so neither cancels the other. When two classes set the same property, the one that wins is the cascade, which is a later lesson.

A class is not a copy of the element#

The class does not contain the heading or the price. The HTML does. The class describes how that content looks. Keep the class about presentation. A class named .latte-450 will be wrong the moment the price changes. .price still describes the label. The next lesson is about the unit on a length, which is part of the type.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.