What is the difference between id and class attributes?
An id names one unique element (used once per page); a class labels a group of elements and may be reused as often as you like.
Both attributes attach a name to an element so CSS and JavaScript can find it, but they answer different needs. An id must be unique in the document — it identifies one specific element:
<div id="header">...</div>
A class is a reusable label, perfect for applying the same styling to many elements:
<p class="highlight">First paragraph</p>
<p class="highlight">Second paragraph</p>
The practical differences line up like this:
| Aspect | id |
class |
|---|---|---|
| Uniqueness | Must be unique on the page | Can repeat freely |
| CSS selector | #header (hash) |
.highlight (dot) |
| Specificity | Higher — wins styling conflicts | Lower |
| URL fragment | Can be a link target: page.html#header |
Not usable as a link target |
A useful rule of thumb: reach for class by default when styling, and use id only when you genuinely need to single out one element — for instance the main content area or the target of an internal # link. An element can carry both at once: <div id="main" class="container">.