In HTML, class is used to style or select multiple elements, while id uniquely identifies a single element—each with different syntax for use in CSS and JavaScript.
April 3, 2025
Photo by Brian McGowan on Unsplash
If you're learning HTML and CSS, you've probably seen class
and id
everywhere—but what's the actual difference?
And when should you use one over the other?
Let’s break it down with simple explanations and examples.
Think of it like this:
<!-- Class example -->
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<!-- ID example -->
<div id="special-box">I’m unique</div>
You can reuse the class .box
as many times as you want, but there should only be one element with the ID special-box
.
/* Class selector: use a dot */
.box {
background-color: lightblue;
}
/* ID selector: use a hash */
#special-box {
border: 2px solid black;
}
Use a dot for class (e.g..box
)
Use a hash for ID (e.g.#special-box
)
// Target a class
const allBoxes = document.querySelectorAll('.box');
// Target an ID
const specialBox = document.querySelector('#special-box');
Classes let you work with groups of elements. IDs let you target one specific thing.
Use class when:
Use id when:
Here’s a quick side-by-side comparison:
class
: Yes, you can use it on many elements.id
: No, it should be unique per page.
class
: Use a dot like .classname
id
: Use a hash like #idname
class
: Use document.querySelectorAll('.classname')
to select all matching elements.id
: Use document.querySelector('#idname')
to select a specific element.Both class
and id
are useful, and knowing when to use each makes your HTML and CSS cleaner and more powerful.
If you're ever unsure, ask yourself: “Will I use this more than once?” If yes, go with a class
.