Class vs ID Selector in CSS and Their Precedence
Both class and ID selectors are used to target elements in CSS, but they differ in usage, specificity, and how often they should be used. The ID selector has higher specificity than the class selector and therefore takes precedence when both apply to the same element.
Begins with a dot (e.g., .button).
Can be applied to multiple elements on a page.
Ideal for reusable styling across many elements.
Specificity score: 0-0-1
Begins with a hash (#) symbol (e.g., #header).
Must be unique and applied to only one element per page.
Best for targeting a specific unique element.
Specificity score: 0-1-0
Because an ID selector has a higher specificity score than a class selector, it will override class styles when both are applied to the same element unless a class selector uses !important.
You have a button with class "primary" that sets background: blue, and the same button also has id "submitBtn" that sets background: red. Which color will the browser display and why?
If you need to change the text color for just one specific card element that already has a .card class, how would you write the selector to ensure your rule wins?
During a feature rollout you notice a new .alert class you added isn’t changing the border color because an existing #globalAlert rule is overriding it. Walk me through how you would debug this and what change you’d make.
When refactoring a component library you have to decide whether to use IDs for theming hooks or stick with classes. What trade‑offs do you consider regarding specificity, reusability, and maintainability?
In a large single‑page application that uses CSS modules, you see a mix of global IDs and component‑scoped classes causing unexpected style overrides. How would you reorganize the CSS to keep specificity predictable and bundle size low?
Your team inherits a legacy codebase that heavily relies on ID selectors for layout. Describe a strategy to migrate to a class‑based approach without breaking existing pages.
The organization is moving from a monolithic stylesheet to a design system built with CSS‑in‑JS. How would you plan the migration of thousands of ID‑based selectors to class‑based or utility‑first patterns across multiple product teams while minimizing visual regressions?
Discuss the long‑term architectural implications of using ID selectors for layout versus a utility‑class system in a product that scales to millions of pages. What risks and benefits do you see?