Both id and class are attributes used to select and style HTML elements, but they have different purposes and behaviors.
1️⃣ id (Unique Identifier)
✅ Used for a single, unique element.
✅ Cannot be reused on multiple elements.
✅ Must be unique in a page.
✅ Has higher specificity in CSS.
Example of id
<p id="unique-text">This is a unique paragraph.</p>
CSS for id
#unique-text {
color: blue;
}
📌 Note: Since id is unique, only one element should have this id.
2️⃣ class (Reusable Styling)
✅ Can be used on multiple elements.
✅ Allows grouping elements for styling.
✅ Lower specificity compared to id.
✅ Preferred for CSS and JavaScript selectors.
Example of class
<p class="highlight">This is a highlighted paragraph.</p>
<p class="highlight">This is another highlighted paragraph.</p>
CSS for class
.highlight {
background-color: yellow;
}
📌 Multiple elements can share the same class, making styling easier.
🔹 Key Differences Between id & class
| Feature | id | class |
|---|---|---|
| Uniqueness | Must be unique (one per page) | Can be reused on multiple elements |
| CSS Selector | #id-name | .class-name |
| Specificity | Higher (overrides class) | Lower (can be overridden by id) |
| Best Use Case | Single, unique elements (e.g., #header, #logo) | Grouping multiple elements (e.g., .button, .text) |
🔹 Example Using Both id & class
<div id="main-container" class="content-box">
<p class="highlight">This is styled using a class.</p>
<p class="highlight">Another paragraph with the same class.</p>
</div>
CSS
#main-container {
border: 2px solid black;
}
.highlight {
color: red;
}
📌 The container has a unique id, while paragraphs share the same class for styling.
🔹 When to Use id vs. class
| Situation | Use id | Use class |
|---|---|---|
| For unique elements (e.g., header, navbar) | ✅ | ❌ |
| For styling multiple elements the same way | ❌ | ✅ |
| For JavaScript DOM manipulation | ✅ (if selecting a single element) | ✅ (if selecting multiple elements) |
Best Practices
✅ Use class for styling (avoid id for CSS, as class is reusable).
✅ Use id for JavaScript selection (if targeting a single element).
✅ Avoid using id and class together unless necessary.
