id vs class is not just selector syntax: it affects fragment links, CSS specificity, JS hooks, and the common mistake of duplicating ids across reusable UI.
What is the difference between id and class attributes in HTML?
Overview
The id and class attributes are not interchangeable. In production, the common mistake is treating both as generic labels: id is a unique identity hook for one node, while class is a reusable grouping hook for styling, behavior, fragment links, and test selectors.
Attribute | Purpose | Usage Scope | Example |
|---|---|---|---|
| Identifies a single, unique element | Can be used only once per page |
|
| Groups multiple elements with a shared style or role | Can be reused across many elements |
|
Example 1: Using id for a unique element
<h1 id="main-title">Welcome to My Website</h1>
<style>
#main-title {
color: royalblue;
text-align: center;
}
</style>
Here, #main-title is a unique selector that applies styles only to that specific heading.
Example 2: Using class for reusable styling
<button class="btn">OK</button>
<button class="btn">Cancel</button>
<style>
.btn {
background-color: teal;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
}
</style>
The class attribute lets you style multiple buttons the same way, making your CSS reusable and consistent.
Key Differences
idmust be unique — each value can appear only once per HTML document.classcan be shared by any number of elements.idis selected in CSS with#(e.g.#header), whileclassis selected with.(e.g..btn).idis often used for JavaScript targeting or page anchors;classis used for styling and grouping.
Think of id as a name tag — one per person.<br>And class as a team jersey — many people can wear the same one.
iduniquely identifies one element per page.classgroups elements that share styles or behavior.- Use
idfor single targets (anchors, JS hooks). - Use
classfor reusable styles and layouts.
Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.