Skip to content

Class (HTML)

In one line

The class attribute assigns a label to an HTML element so it can be styled or selected together with others.

In simple words

The class attribute lets you group HTML elements under a shared name. You can then style all elements with that class using a single CSS rule, or select them all at once in JavaScript. This is the primary way to apply reusable styles across a page.

A class is written as class="button" on the element, and targeted in CSS with a dot: .button { ... }. An element can have multiple classes separated by spaces: class="button primary large". This lets you combine styles modularly.

Unlike IDs, classes are not unique — many elements can share the same class. This makes classes the right choice for repeating components like buttons, cards, or list items.

Example

html
<button class="btn btn-primary">Save</button>
<button class="btn btn-secondary">Cancel</button>

<style>
  .btn { padding: 8px 16px; border-radius: 4px; }
  .btn-primary { background: #2563eb; color: white; }
  .btn-secondary { background: gray; color: white; }
</style>

Both buttons share the btn class for base styling, and each has a second class for its variant.

Common confusions

  • Confused with: id

    The difference: A class can be shared by many elements and is targeted with .class in CSS; an id must be unique on the page and is targeted with #id. Use classes for reusable styles, ids for single specific elements.

Related terms

Related Resources

Related Lessons

  • CSS

    Classes are the most common CSS targeting mechanism

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary