HTML Classes
The HTML class attribute labels one or more elements so CSS or JavaScript can find them. A class name can be reused on multiple elements.
Add a class to HTML
<h2 class="section-title">Getting started</h2>
<p class="section-title">A short introduction.</p>
Select the class in CSS
Begin a class selector with a period. This rule applies to every element whose class list contains section-title.
.section-title {
color: #203044;
margin-bottom: 1rem;
}
An element can have more than one class. Separate class names with spaces, for example class="card featured".
Combine class names in CSS
Class values are a space-separated list. To style an element only when it has both card and featured, write a selector with no space between the class selectors:
.card.featured {
border-color: #a74800;
}
A space means something different: .card .featured selects an element with class featured inside another element with class card.
Use classes from JavaScript
JavaScript can add, remove, or toggle a class without replacing the element’s content. This is useful for states such as an expanded menu or a selected tab.
const panel = document.querySelector(".details");
panel.classList.toggle("is-open");
Use a class for reusable styling or state. Use a unique ID when a particular element needs a unique target, such as a fragment link.
HTML class questions
Can one element have more than one class?
Yes. Separate class names with spaces, for example class="card featured". Each name can be selected and styled independently.
What is the difference between a class and an ID?
A class can be shared by many elements. An ID should identify one element within the page. Use classes for reusable styles and IDs for unique targets.