Classes & IDs

You've seen class and id already in passing. This lesson is about the difference between them and when to reach for each one — it trips people up more than it should.

class: for groups

Any number of elements can share the same class, and one element can have several classes at once, separated by spaces. That's what makes classes the right tool for reusable styling — "every warning message" or "every card":

Try it yourself
Result

id: for one specific element

An id must be unique within the page — no two elements should share one. That uniqueness is what makes an id useful for two jobs a class can't do well: linking straight to a spot on the page with a # URL, and grabbing one exact element in JavaScript with document.getElementById().

Try it yourself
Result

Rule of thumb

  • Reach for class when the same styling or behavior applies to more than one element, or might in the future.
  • Reach for id only when you genuinely mean one specific, singular element — a page's main heading, a form's single submit button that JavaScript needs to find.
Note: browsers won't stop you from reusing an id on multiple elements, but tools that rely on it — getElementById, # links, CSS #id selectors — will only ever find the first match. Duplicate ids are a real, easy-to-miss bug.