An id is unique on a page and selected with #id; a class can be reused and selected with .class. IDs have higher specificity and are often used for anchors or JS hooks, while classes are for styling groups.
What is the difference between id and class selectors?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
In CSS, id and class selectors target elements for styling or scripting, but they serve different purposes. IDs are unique identifiers for single elements, while classes group multiple elements under a shared style.
Aspect | id Selector | class Selector |
|---|---|---|
Syntax | elementID | .elementClass |
Uniqueness | Must be unique per page | Can be used on multiple elements |
Specificity | Higher (overrides class styles) | Lower (can be overridden by id) |
Use Case | For specific, unique components | For reusable, shared styles |
Example HTML | <div id='header'> | <div class='card'> |
Example: Styling with id and class
#header {
background: #0ea5e9;
color: white;
}
.card {
border: 1px solid #cbd5e1;
padding: 12px;
border-radius: 6px;
}
Here, #header targets a unique section, while .card can style multiple elements throughout the page.
Best Practices
- Use
idfor elements that occur only once (like navigation bars or main headers). - Use
classfor groups of similar elements that share styling. - Avoid overusing IDs in CSS — they increase specificity and reduce maintainability.
- Use
classselectors in component-based systems like React or Angular for modularity.
Specificity Hierarchy
CSS calculates priority using a scoring system. IDs (100 points) outrank classes (10 points). Inline styles override both, but using classes promotes flexibility and scalability.
Think of id as your unique name (only one of you), and class as your role or group — many people can share the same role.
idis unique and used once per page.classis reusable across elements.- IDs have higher specificity; use sparingly for maintainability.
- Use classes for scalable, component-based design.