What is an ID in HTML?
The id attribute uniquely identifies a single HTML element on a page.
Each ID value should only appear once in a document.
<h1 id="main-title"> Welcome </h1>
IDs are commonly used for:
- Unique page sections
- Anchor links
- JavaScript targeting
- Accessibility relationships
An ID should be unique. Multiple elements should not share the same ID value.
What is a class in HTML?
The class attribute groups elements together.
Unlike IDs, classes are reusable and can appear on many elements.
<div class="card"> Card 1 </div> <div class="card"> Card 2 </div>
Both elements share the same class and can be styled together.
CSS selectors for IDs and classes
CSS uses different selector syntax for IDs and classes.
/* ID selector */ #main-title { color: navy; } /* Class selector */ .card { padding: 1rem; border-radius: 12px; }
#targets IDs.targets classes
Main difference between ID and class
The biggest difference is uniqueness and reusability.
<!-- Unique element --> <header id="site-header"> ... </header> <!-- Reusable styling --> <div class="card"> ... </div> <div class="card"> ... </div>
When should you use IDs?
Use IDs for unique page elements.
Examples include:
- Main navigation
- Hero section
- Modal containers
- Anchor links
- JavaScript hooks
<section id="about"> ... </section> <a href="#about"> About </a>
When should you use classes?
Use classes for reusable styling and grouping.
Most modern CSS is built almost entirely with classes.
- Buttons
- Cards
- Layouts
- Typography styles
- Utility classes
Frameworks like Bootstrap and Tailwind CSS rely heavily on classes rather than IDs.
CSS specificity differences
IDs have higher CSS specificity than classes.
This means ID styles are harder to override.
#title { color: red; } .title { color: blue; }
The ID selector will win because it has higher specificity.
Avoid styling large websites primarily with IDs because high specificity can make CSS difficult to maintain.
Can an element have both an ID and class?
Yes. Elements can use both attributes together.
<button id="signup-btn" class="btn primary-btn" > Sign Up </button>
Here:
- The ID uniquely identifies the button.
- The classes apply reusable styles.
Common beginner mistakes
- Using the same ID multiple times
- Using IDs for all CSS styling
- Forgetting that classes are reusable
- Confusing
#and.selectors
Summary
IDs and classes are both important HTML attributes, but they serve different purposes.
- ID = unique identifier
- Class = reusable grouping and styling
Modern web development usually prefers classes for CSS and uses IDs mainly for unique elements, navigation anchors, and JavaScript targeting.
Ready to master HTML and CSS? Our free courses cover selectors, specificity, semantic HTML, layouts, and modern web development step-by-step.