Classes
Create reusable styles by grouping HTML elements together with CSS classes.
color: #20e778;
}
<p class=“highlight”>
Hello!
</p>
>_ What Is an HTML Class?
A class is a reusable name that you can assign to one or more HTML elements. CSS can then use that class to apply the same style to every matching element.
This becomes especially useful as webpages grow. Instead of repeating the same inline style over and over, you can create a class once and reuse it.
Assign a Class
Use the class attribute inside an HTML opening tag to give an element a class name.
Select the Class
In CSS, a period before the class name creates a class selector.
Reuse Styles
Multiple elements can share the same class and automatically receive the same styles.
>_ Giving an Element a Class
Classes are added with the class attribute.
This paragraph is important.
</p>
Here, the paragraph belongs to a class named highlight.
>_ Creating a Class Style
For this lesson, we’ll place CSS inside a <style> element in the page’s <head>.
To select a class in CSS, place a period (.) before its name.
.highlight {
color: #087b49;
font-weight: bold;
}
</style>
>_ Connecting HTML and CSS
The class name in your HTML must match the class selector in your CSS.
class="highlight"
Assigns the HTML element to the highlight class.
.highlight
Selects every element that belongs to the highlight class.
{ }
Curly braces contain the CSS rules that should be applied.
color: ...;
A CSS declaration changes the appearance of every matching element.
>_ One Class, Multiple Elements
The real power of classes is that the same class can be reused.
Important Heading
</h2>
<p class=“highlight”>
Important paragraph.
</p>
Both elements now receive the styles defined by .highlight.
>_ Using More Than One Class
An element can even belong to multiple classes. Separate each class name with a space.
class=“highlight centered”
>
Two classes!
</p>
HTML uses class="highlight",
while CSS selects that class with
.highlight. The period belongs
in the CSS selector — not inside the HTML
class attribute.
Build Reusable Message Styles
Create reusable CSS classes for success messages and important notes.
-
✓
Create a class named
.success. -
✓
Give
.successa green color and light green background. -
✓
Create another class named
.important. -
✓
Make
.importantbold and blue. -
✓
Apply
successto two different paragraphs. - ✓ Apply both classes to one element.
Classes Challenge
What You’ve Learned
class="".
.success.
Nice work!
Finished this lesson? Mark it complete to track your progress.


