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.
Use this CSS interview question to rehearse a quick answer, common mistake, follow-up, and production pitfall.
What is the difference between id and class selectors?Frontend interview answer
This CSS interview question tests whether you can explain id vs class Selectors in CSS: Differences and Specificity, connect it to production trade-offs, and handle common follow-up questions.
- id vs class Selectors in CSS: Differences and Specificity explanation without falling back to memorized docs wording
- Selectors and Id reasoning, edge cases, and production failure modes
- How you would answer the most likely CSS interview follow-up
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.
Use this as one explanation rep, then continue with the CSS interview questions cluster or a guided prep path.