Skip to main content
Syllabus

HTML Classes vs ID: Selectors Explained

Badar KhalilUpdated September 27, 2026 2 min read

HTML Classes vs ID: Understanding Selectors

Focus keyword: HTML class vs id — one of the most common points of confusion for beginners learning to structure and style web pages.

Both class and id are HTML attributes used to identify elements so they can be targeted by CSS or JavaScript. However, they behave very differently.

1. The class Attribute

A class can be applied to multiple elements on the same page, and a single element can have multiple classes separated by spaces. Classes are ideal for reusable styling — e.g., every button on your site sharing a .btn class.

2. The id Attribute

An id must be unique within a page — no two elements should share the same id. IDs are used for a single specific element, such as a page's main navigation bar, or as an anchor target for in-page links (#section-name).

3. CSS Specificity: Why It Matters

In CSS, id selectors (#header) have higher specificity than class selectors (.header), meaning id styles override class styles when both target the same element. This is a key concept in the trending topic of CSS specificity and the cascade.

4. Quick Comparison Table

Featureclassid
UniquenessReusable, many elementsMust be unique per page
CSS selector.classname#idname
JS selectordocument.querySelectorAll('.name')document.getElementById('name')
SpecificityLowerHigher

5. Best Practices

  • Use class for anything reusable (buttons, cards, badges)
  • Use id sparingly — mainly for JS hooks, anchor links, or form labels (for/id pairing)
  • Avoid using id for styling when a class would work, to keep CSS specificity manageable — a widely recommended modern CSS architecture practice (e.g., BEM methodology)
Try it Yourself HTML
Output

Press Run to execute.

Try it Yourself CSS
Output

Press Run to execute.

Try it Yourself JAVASCRIPT
Output

Press Run to execute.

Exercise: Fix the Duplicate ID BugHTML

The code below mistakenly uses the same id on three buttons. Fix it by converting them to a shared class, and add one unique id only on the container div.

Try it Yourself HTML
Output

Press Run to execute.

Show expected output
All three buttons share a class (e.g. class='action-btn'), no duplicate ids remain, and the wrapping div has one unique id.

This is a self-check — compare your result with the expected output above.

Quiz: Classes vs ID Quiz Pass 70%
Loading quiz…

Was this page helpful?