Best Practices around Using Classes vs IDs

You may have seen class and id in your HTML and wondered: What's the actual difference? When should I use one over the other? Let's break it down together.

HTML & CSS: The House Analogy

Think of HTML as the blueprint of a house. It tells the browser what to build. CSS is the decorator or builder. It paints the walls, adds curtains, and arranges the furniture.

But how does CSS know which part of the house to decorate? That's where classes and ids come in.

What is a Class?

A class is a label you can reuse on many elements. All elements with that class will share the same styles.

Syntax: In HTML use class="something". In CSS use a dot (.).

<button class="btn">Save</button>
<button class="btn">Cancel</button>
.btn {
  background-color: blue;
  color: white;
  padding: 10px;
  border-radius: 6px;
}

Both buttons share the same look thanks to the .btn class.

What is an ID?

An id is like a unique name tag. Each id can only appear once on a page.

Syntax: In HTML use id="something". In CSS use a hash (#).

<h1 id="main-title">Welcome to My Blog</h1>
#main-title {
  font-size: 2.5rem;
  color: darkgreen;
}

Only the one element with id="main-title" gets this styling.

Classes vs IDs: Quick Comparison

Feature Class (.class) ID (#id)
Uniqueness Reusable on many elements Must be unique (once per page)
Specificity Lower (easy to override) Higher (harder to override)
Best for… Buttons, cards, nav links, repeated styles Unique sections like headers or footers
Use in CSS .classname { ... } #idname { ... }
Use in JavaScript document.querySelector('.classname') (many) document.getElementById('idname') (one)

Best Practices


If you're ever unsure just ask yourself: is this style going on more than one element? If yes use a class. If it's only for one specific element an ID is fine.