HTML & CSS Interview Question #26
What is the difference between the id and class attributes in HTML?
Forms, Validation, Metadata, Media, Responsive Images & Accessibility Junior Beginner
Quick Interview Answer
The id attribute identifies an element with a document-wide identifier, while class assigns one or more reusable class names. CSS and JavaScript can use both, but classes are normally preferred for reusable styling.
Detailed Explanation
The id attribute identifies an element with a document-wide identifier, while class assigns one or more reusable class names. CSS and JavaScript can use both, but classes are normally preferred for reusable styling.
An id should be unique within the document. The same class can be applied to many elements. IDs are also useful as fragment targets, label associations, ARIA references, and other relationships that require a specific element.
Code Example
<section id="featured-products" class="product-section">
<article class="product-card">Projector</article>
<article class="product-card">Dash Cam</article>
</section>