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

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