A class lets you give a group of elements a name and style them together. You add the name in HTML with the class attribute, and you select it in CSS with a dot.
<style>
.note {
background: #fff3cd;
border-left: 4px solid #e0a800;
padding: 10px 14px;
}
</style>
<p>Normal paragraph.</p>
<p class="note">This one is a note.</p>
<p>Another normal paragraph.</p>
<p class="note">And this is a second note.</p>
.note matches any element that has class="note", whatever its tag is. A class can be reused as many times as you like.
Several classes on one element
An element can carry more than one class, separated by spaces.
<style>
.note { padding: 10px 14px; background: #eef; }
.important { font-weight: bold; color: #b00020; }
</style>
<p class="note">A plain note.</p>
<p class="note important">A note that is also important.</p>
This lets you build small, reusable pieces and combine them, instead of writing a new rule for every case.
Limit a class to one tag
You can combine an element name and a class with no space between them. p.note only matches paragraphs with the class note.
p.note { margin-bottom: 0; }
Name classes by purpose
.note, .card and .button-primary still make sense after a redesign. .red-text does not once the color changes. More on this in Naming CSS Classes.Forgetting the dot
note { ... } looks for an element called <note>, which does not exist. The dot is what tells CSS “this is a class”.Exercise: a highlight class
Create a class called highlight with a yellow background, and apply it to one word inside a paragraph using <span>.
Show a possible solution
<style>
.highlight { background: yellow; }
</style>
<p>This is <span class="highlight">important</span> text.</p>