HTML global attributeGlobal attributes

class

A list of class names that CSS and JavaScript use to find an element.

Applies to
All HTML elements
On this page

Example

#
HTML
<style>
  .card { padding: 12px 16px; border-radius: 12px; border: 1px solid #333; }
  .card-highlight { border-color: #a78bfa; background: #1e1533; }
</style>

<p class="card">A regular card</p>
<p class="card card-highlight">A card highlighted with two classes</p>
Preview

Definition and usage

#

The class attribute assigns an element one or more class names, separated by spaces. Classes alone change nothing about how an element looks. They only gain meaning when you refer to them in CSS (the .name selector) or in JavaScript.

The same class can appear on many elements, and one element can have many classes. This lets you combine styles like building blocks: class="btn btn-primary btn-large" is a button with the shared look, the primary color, and a large size.

In JavaScript, the most convenient way to manage classes is element.classList: the add(), remove(), toggle() and contains() methods save you from gluing strings together by hand.

Syntax

#
Syntax
<element class="name another-name">…</element>

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Name classes after their role, not their looks: .alert-error survives a color change, .red-text does not.
  • Case matters: Card and card are two different classes.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.