Episode 14 of 17

Classes vs IDs in HTML

Understand the difference between classes and IDs in HTML — when to use each, naming conventions, and how they work with CSS and JavaScript.

Classes and IDs are attributes that let you identify and target HTML elements for styling (CSS) and interactivity (JavaScript).

The class Attribute

Classes are reusable. Multiple elements can share the same class:

<p class="highlight">First highlighted text</p>
<p class="highlight">Second highlighted text</p>
<p>Normal text</p>

An element can have multiple classes separated by spaces:

<div class="card featured large">...</div>

The id Attribute

IDs are unique. Only one element per page should have a specific ID:

<div id="main-header">...</div>
<section id="about">...</section>

Classes vs IDs Comparison

Featureclassid
Reusable?Yes — many elementsNo — unique per page
CSS selector.classname#idname
SpecificityLowerHigher
JavaScriptquerySelectorAllgetElementById
Best forStyling groupsUnique elements

Using with CSS

/* Target by class */
.highlight { background: yellow; }

/* Target by ID */
#main-header { background: navy; color: white; }

Naming Conventions

  • Use lowercase with hyphens: class="card-title"
  • Be descriptive: class="nav-link" not class="nl"
  • Avoid numbers at the start: class="item-1" ✅, class="1-item"

Rule of Thumb

Use classes 95% of the time. Use IDs only for unique elements like a main header, or for JavaScript targeting and anchor links.