What is the difference between id and class in HTML?

id is unique only one element per page; class is reusable any number of elements can share it.

HTMLCSS

Overview

Both `id` and `class` are HTML attributes used to target elements with CSS or JavaScript. The key difference is uniqueness: an `id` must be unique on the page, while a `class` can be applied to as many elements as you like.

Key Points

  • •`id` must be unique per page. Use for page anchors, form label associations, and JS querySelector targets.
  • •`class` is reusable. Use for styling patterns shared across multiple elements.
  • •CSS specificity: `id` selectors (#name) are more specific than class selectors (.name) they override class styles.
  • •An element can have multiple classes: `class="btn btn-primary large"`.
  • •JavaScript: `getElementById` is faster than `querySelector` but only works with ids.

Examples

id for unique elements, class for repeated patterns

html
<header id="main-header">...</header>  <!-- unique, used once -->

<button class="btn btn-primary">Save</button>   <!-- reusable -->
<button class="btn btn-secondary">Cancel</button>

CSS specificity: id overrides class

css
.text { color: blue; }
#warning { color: red; } /* wins even if .text comes later in the file */

JavaScript targeting

javascript
// By id (unique)
const header = document.getElementById('main-header');

// By class (returns all matching elements)
const buttons = document.querySelectorAll('.btn');

Pro Tip

In modern CSS, prefer classes for styling and avoid over-using ids for CSS selectors their high specificity creates "specificity wars" that are hard to override. Reserve ids for anchors (`<a href="#section">`) and ARIA relationships (`<label for="email-input">`).