Skip to content

HTML Class vs ID Tutorial for Beginners

HTML class and id attributes are used to identify, style, select, and control HTML elements. In this lesson, you will learn the difference between class and id, when to use each one, CSS and JavaScript examples, dynamic IDs from Java, ASP.NET, PHP, and modern frameworks, accessibility tips, SEO considerations, and common mistakes.

What Are Class and ID in HTML?

The class and id attributes are global HTML attributes. They can be added to most HTML elements to identify them for CSS, JavaScript, testing, accessibility relationships, bookmarks, and component behavior.

<section id="about" class="content-section highlighted">
  <h2>About Us</h2>
  <p>This section uses both id and class attributes.</p>
</section>

HTML Class vs ID Cheatsheet

The following table explains the most important differences between class and id.

Comparison Class ID
Purpose Groups one or more elements. Identifies one unique element.
HTML Example <p class="note">Text</p> <p id="intro">Text</p>
CSS Selector .note { color: blue; } #intro { color: red; }
JavaScript Selector document.querySelector(".note") document.getElementById("intro")
Reusability Can be reused on many elements. Should be unique on the page.
Multiple Values One element can have multiple classes. One element should have one id value.
Best For Styling groups, components, utilities, states. Anchors, labels, scripts, unique sections.
CSS Specificity Lower specificity. Higher specificity.
URL Fragment Not used directly for page jumps. Used with links like #contact.
Recommendation Use often for styling. Use only when uniqueness is required.

HTML Class Attribute

The class attribute groups elements so they can share the same CSS styles or JavaScript behavior. A class can be reused many times on the same page.

<div class="card">
  <h2 class="card-title">HTML Basics</h2>
  <p class="card-text">Learn the building blocks of HTML.</p>
</div>

<div class="card">
  <h2 class="card-title">CSS Basics</h2>
  <p class="card-text">Learn how to style web pages.</p>
</div>
.card {
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 0.75rem;
}

.card-title {
  font-size: 1.25rem;
}

HTML ID Attribute

The id attribute uniquely identifies one element on a page. IDs are commonly used for page anchors, form labels, JavaScript selection, ARIA relationships, and unique page sections.

<section id="contact">
  <h2>Contact Us</h2>
  <p>Use this section for contact details.</p>
</section>

<a href="#contact">Go to Contact Section</a>
#contact {
  scroll-margin-top: 90px;
}

Using Multiple Classes on One Element

One HTML element can have multiple classes separated by spaces. This is useful for combining component styles, utility classes, and state styles.

<button class="btn btn-primary is-active">
  Save Changes
</button>
.btn {
  padding: 0.75rem 1rem;
  border-radius: 0.5rem;
}

.btn-primary {
  font-weight: 700;
}

.is-active {
  outline: 2px solid currentColor;
}

Class vs ID in CSS Specificity

ID selectors have higher CSS specificity than class selectors. Because of this, using IDs for styling can make CSS harder to override and maintain.

.title {
  color: blue;
}

#title {
  color: red;
}

If both rules target the same element, the ID selector usually wins because it has higher specificity.

Class and ID in JavaScript

JavaScript can select elements using classes or IDs. Use IDs when you need one specific element. Use classes when you need to select one or many related elements.

const menu = document.getElementById("mainMenu");

const cards = document.querySelectorAll(".card");

cards.forEach((card) => {
  card.classList.add("is-visible");
});

ID Usage with Form Labels

Form labels use the for attribute to connect to an input id. This improves accessibility and allows users to click the label to focus the input.

<label for="email">Email Address</label>
<input id="email" name="email" type="email" />

ID Usage with ARIA Relationships

ARIA attributes often reference IDs to connect controls with descriptions, error messages, tabs, panels, or expanded content.

<label for="password">Password</label>
<input
  id="password"
  type="password"
  aria-describedby="passwordHelp"
/>

<p id="passwordHelp">Use at least 8 characters.</p>

Dynamically Generated IDs in Java, ASP.NET, PHP, and Frameworks

In server-side and component-based applications, IDs are often generated dynamically. This is common when rendering lists, forms, tables, reusable components, or database records. Dynamic IDs must still be unique in the final HTML output.

Technology Dynamic ID Example Common Use Case
Java / JSP id="user-<?= $user['id']; ?>" Rendering database records or user rows.
ASP.NET Web Forms ClientIDMode="Static" Controlling generated client-side IDs.
ASP.NET Razor id="product-@Model.Id" Generating IDs from model data.
PHP id="post-<?= $post['id']; ?>" Rendering posts, comments, or products.
React id={`field-${inputId}`} Component-level ID generation.
Angular [id]="'item-' + item.id" Binding IDs from component data.
Vue :id={`user-${user.id}`} Binding dynamic IDs in templates.
Astro id={`section-${slug}`} Generating IDs for headings and sections.

When generating dynamic IDs, use stable values such as database IDs, slugs, UUIDs, or predictable component identifiers. Avoid random IDs when the ID must match a label, ARIA relationship, test selector, or anchor link.

Dynamic ID Examples

PHP Dynamic ID Example

<?php foreach ($posts as $post): ?>
  <article id="post-<?= $post['id']; ?>" class="post-card">
    <h2><?= htmlspecialchars($post['title']); ?></h2>
  </article>
<?php endforeach; ?>

Java / JSP Dynamic ID Example

<c:forEach var="user" items="{users}">
  <tr id="user-{user.id}" class="user-row">
    <td>{user.name}</td>
  </tr>
</c:forEach>

ASP.NET Razor Dynamic ID Example

@foreach (var product in Model.Products)
{
  <section id="product-@product.Id" class="product-card">
    <h2>@product.Name</h2>
  </section>
}

React Dynamic ID Example

function EmailField({ id }) {
	const inputId = `email-${id}`;

  return (
    <div className="form-field">
      <label htmlFor={inputId}>Email</label>
      <input id={inputId} name="email" type="email" />
    </div>
  );
}

HTML Class and ID Best Practices

  • Use classes for reusable styling and component states.
  • Use IDs for unique sections, form labels, ARIA relationships, and anchors.
  • Keep ID values unique on the page.
  • Avoid using IDs heavily for CSS styling because they are harder to override.
  • Use meaningful names like main-content, email, or product-card.
  • Avoid spaces in class and ID values.
  • Use stable IDs when linking labels, error messages, or anchor links.
  • Do not generate duplicate IDs in loops or reusable components.

SEO and Accessibility Considerations

Classes and IDs do not directly rank a page, but they support clean structure, accessibility relationships, anchor navigation, JavaScript behavior, and maintainable components.

  • Use IDs for heading anchors and table of contents links.
  • Use IDs to connect labels with form fields.
  • Use IDs with aria-describedby for help text and error messages.
  • Use classes to create reusable, consistent UI styles.
  • Keep names meaningful for long-term maintainability.

Common Class and ID Mistakes

  • Using the same ID multiple times on one page.
  • Using IDs for every CSS style.
  • Using unclear names like box1, red, or abc.
  • Changing dynamic IDs on every render when labels or ARIA rely on them.
  • Using class names that describe only color instead of purpose.
  • Forgetting to update label for when changing input IDs.
  • Using JavaScript selectors that break when class names change.

Key Takeaways

  • Use class for reusable styles and groups of elements.
  • Use id for one unique element on a page.
  • Classes use the . selector in CSS, while IDs use the # selector.
  • IDs are useful for anchors, labels, ARIA relationships, and JavaScript selection.
  • Dynamic IDs are common in Java, ASP.NET, PHP, React, Angular, Vue, and Astro.
  • Always make dynamically generated IDs unique, stable, and meaningful.

Pro Tip

Use classes for styling and reusable UI patterns. Use IDs only when you need a unique target for labels, anchors, ARIA, or JavaScript.