Classes & IDs

The class and id attributes give elements names that CSS and JavaScript can target. A class labels a group of elements that share something; an id identifies one specific element. Knowing when to use each keeps code tidy and predictable.

class: for groups

Try it yourself
Result
  • Many elements can share a class.
  • One element can have several classes, separated by spaces: class="note warning".
  • In CSS, a class is selected with a dot: .note.

id: for one element

Try it yourself
Result
  • An id must be unique on the page — no two elements may share one.
  • An element can have only one id.
  • In CSS, an id is selected with a hash: #site-title.

What ids are good for

UseExample
Link targets (fragments)<a href="#faq"> jumps to id="faq"
Connecting form labels to inputs<label for="email"> + <input id="email">
ARIA relationshipsaria-describedby="hint"
JavaScript lookupsdocument.getElementById("cart")

For styling, prefer classes. CSS rules using ids are very "specific" — they override class rules in ways that become hard to manage — and an id style can't be reused on a second element.

Naming well

Names can contain letters, digits, hyphens and underscores. Good names describe what something is, not what it looks like:

HTML naming.html
<p class="error-message">…</p>   <!-- ✓ describes purpose -->
<p class="red-bold-text">…</p>   <!-- ✗ describes appearance -->

If the design changes so errors become orange, error-message still makes sense; red-bold-text becomes a lie. Use lowercase words separated by hyphens (kebab-case), the most common convention.

Naming conventions in larger projects

Teams often adopt a convention to keep class names organised. One popular approach is BEM (Block, Element, Modifier):

Try it yourself
Result

card is the block, card__title an element inside it, and card--featured a variation. Utility-first frameworks like Tailwind CSS take a different approach, using many small single-purpose classes such as p-4 and text-center.

Classes for JavaScript

JavaScript uses classes and ids to find elements and to toggle states:

Try it yourself
Result

A state class like is-open describes the element's condition; CSS decides how that looks.

Try it yourself

Try it yourself
Result