What is the difference between the id and class attributes in HTML?
· Category: HTML & CSS
Short answer
The id attribute assigns a unique identifier to a single element, while the class attribute can be shared across multiple elements to apply common styling or behavior.
How it works
An id must be unique within a page and is often used for precise CSS targeting, anchor links, and JavaScript DOM selection. A class is reusable and designed for grouping elements that share visual or functional traits. You can assign multiple classes to one element by separating them with spaces.
Example
<!-- Unique element -->
<div id="hero-banner">Welcome</div>
<!-- Reusable styling -->
<div class="card featured">Card 1</div>
<div class="card">Card 2</div>
#hero-banner {
font-size: 2rem;
}
.card {
border: 1px solid #ccc;
}
.featured {
background: gold;
}
Why it matters
Using id for one-off elements and class for repeatable patterns keeps your HTML and CSS maintainable. Overusing id for styling can lead to specificity wars and brittle code, whereas class-based architectures scale better in large projects.