#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 8 of 49easy

What is the difference between id and class?

Two ways to identify elements.

What You'll Learn

  • Key differences between id and class
  • CSS specificity implications
  • Best practices for using each

The Key Difference: Uniqueness

  • id - Must be unique on a page (only one element can have it)
  • class - Can be reused (multiple elements can share it)

CSS Specificity

id has higher specificity (100) than class (10), so id styles override class styles.

index.htmlHTML
<style>
  #special { color: red; }    /* specificity: 100 */
  .highlight { color: blue; } /* specificity: 10 */
</style>

<!-- This text will be RED because id wins -->
<p id="special" class="highlight">Hello</p>

HTML Examples

index.htmlHTML
<!-- id: unique identifier -->
<header id="main-header">Only one main header</header>
<form id="contact-form">...</form>

<!-- class: reusable styling -->
<p class="highlight">Styled paragraph</p>
<p class="highlight">Same styling here</p>
<p class="highlight warning">Multiple classes</p>

JavaScript Targeting

code.jsJavaScript
document.getElementById('main-header');        // one element
document.getElementsByClassName('highlight');  // collection
document.querySelector('#main-header');        // one element
document.querySelectorAll('.highlight');       // NodeList

Best Practice

  • Use class for styling (more flexible, reusable)
  • Reserve id for unique elements that JavaScript needs to target