HTML: the class attribute
The class attribute assigns one or more reusable names to elements so CSS and JavaScript can work with a group of elements.
What you will learn
- How to group elements with reusable class names
- How CSS and JavaScript use classes
- How role-based names make styles and scripts easier to maintain
Basic example
<p class="notice">Your settings were saved.</p>
<p class="notice notice--warning">Check your email address.</p>
.notice {
padding: 1rem;
}
.notice--warning {
border: 2px solid darkorange;
}
Both paragraphs share the notice class. The second also has a modifier class that describes a variation of that role.
Use more than one class
<button class="button button--primary" type="button">
Save
</button>
Separate class names with spaces. Each class can represent a reusable role, component, or state. Avoid names such as red-text when the class is really meant to describe a warning or error.
JavaScript and classes
const message = document.querySelector('.notice');
message.classList.add('notice--visible');
message.classList.remove('notice--hidden');
JavaScript can read and change classes with classList. Keep behavior-specific hooks stable and do not make scripts depend on fragile visual styling names.
Common mistakes
- Using a class as a replacement for a meaningful element such as
<button>or<nav>. - Choosing names based only on current color or position.
- Putting several unrelated responsibilities into one class name.
- Using a class when a unique
idis required for a label relationship or fragment link.