Classes and ID

Learn how to use classes and ids

Classes

Classes are used to apply styles to multiple HTML elements. They are defined with the class attribute and can be assigned to any number of elements. Here is an example:

// HTML
<p class="red">This is a paragraph.</p>
// CSS
.red {
color: red;
}

IDs

IDs are used to uniquely identify a single HTML element. They are defined with the id attribute. Here is an example:

// HTML
<p id="red">This is a paragraph.</p
// CSS
#red {
color: red;
}

Main difference

Classes are used to apply the same style to multiple HTML elements, whereas IDs are used to apply the same style to a single HTML element. Here is an example:

// HTML
<p class="red">This is a paragraph.</p>
<p class="red">This is a paragraph.</p>
<p id="red">This is a paragraph.</p>
// CSS
.red {
color: red;
}
#red {
color: red;
}