The class attribute accepts a space-separated list of tokens. Classes power CSS selectors, testing hooks, and occasionally JavaScript queries—reuse them liberally compared to unique IDs.
<button class="btn btn-primary">Save</button>
Naming strategies
- Components:
.card,.card__title,.card--featured(BEM-inspired). - Utility stacks: multiple atomic classes composed together.
- Scoped CSS frameworks: generated hashes prevent collisions automatically.
Multiple classes
Order among tokens rarely matters to CSS unless specificity tricks appear—still, keep conventions stable (component state ordering).
Don’t encode measurements
Avoid class names like mt-16px unless generated—design tokens change; semantics shouldn’t.
JavaScript hooks
Some teams prefix hook classes (js-modal-open) to signal behavioral coupling separate from styling layers.
What maintainers curse later
- Components exporting dozens of unordered classes—“utility soup”—hard to grep meaningful state.
- Using classes as versioning (
.v2) tied to brittle CSS descendant selectors rather than encapsulation boundaries.
BEM / utilities / CSS-in-JS
Pick one primary strategy per surface area; hybrids exist but undocumented mixes confuse juniors during refactors.
Rendered — same element, different class stacks
<button class="rounded-lg bg-indigo-600 px-4 py-2 text-white">Save</button>
<button class="rounded-lg border-2 border-dashed border-zinc-400 px-4 py-2">Draft</button>
Important interview questions and answers
- Q: What is the practical difference between `id` and `class`?
A: `id` must be unique and is used for fragments/labeling; `class` is reusable for styling and behavior grouping. - Q: Why is `defer` commonly preferred for scripts?
A: It preserves HTML parsing, executes after parse, and avoids blocking rendering unlike classic synchronous scripts. - Q: How do `srcset` and `sizes` work together?
A: `srcset` provides candidate files and `sizes` tells expected rendered width so the browser can pick an optimal resource.
Tip: Class names describe purpose (card__title), not appearance (red-text).