Modern CSS Best Practices

Chapter 2 · Practice 4 of 4

Scope component styles with a naming convention or @scope

From The cascade, specificity and cascade layers

Why it matters

Global class names collide. A .title in the card component and a .title in the modal will affect each other as soon as both are on the page.

Options, from simplest to most automatic:

  • A naming convention such as BEM: .card__title, .card--featured. Simple and works everywhere.
  • CSS Modules or framework scoped styles, which rewrite class names at build time.
  • Utility classes, as in Tailwind, where styles live on the element and there is little shared CSS to collide.

Whichever you choose, use it consistently. Mixed conventions in one codebase are harder to reason about than any single one. Check the current Baseline status on MDN before relying on the native @scope rule in shared code.