Sub topic 3
Scoping Styles and Maintaining CSS at Scale
Assume you know selectors, specificity, inheritance, the box model, HTML, and basic npm usage. This chapter focuses on controlling which rules can affect which components.
Choose a scoping technique
CSS Modules make class names local to a component file. A build tool changes names such as .root into unique names, preventing collisions.
/* Card.module.css */
.root {
padding: 1rem;
}
.featured {
border: 2px solid gold;
}Shadow DOM creates a browser-enforced boundary around a web component. Outside styles cannot normally enter it, and internal styles cannot normally escape. Use it for reusable widgets that need strong isolation. Use CSS custom properties or ::part() when consumers need controlled customization.
@scope limits selectors to a section of the document without renaming classes.
@scope (.card) {
.title {
color: navy;
}
}This rule affects .title descendants inside .card, not every .title on the page. Check browser support before using it alone in production.
Use utility classes deliberately
A utility class performs one small job, such as .p-0 or .text-center. Utilities are useful for spacing, layout, and occasional overrides. Keep component rules for structure and meaning. Do not replace every component with an unreadable list of utilities.
Enforce conventions with Stylelint
Stylelint checks CSS automatically during development and continuous integration.
{
"extends": "stylelint-config-standard",
"rules": {
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true
}
}Low specificity makes styles easier to override without hacks.
Remove dead CSS safely
Search templates, scripts, and generated content before deleting a selector. Check dynamic class names and alternate routes. Remove unused rules in small commits, then compare visual tests and production pages.
Bundle and document styles
A build pipeline can combine shared CSS, split route-specific CSS, minify it, and produce hashed files for caching. Load critical styles early and defer noncritical styles when appropriate.
Document tokens, component states, required classes, accessibility rules, and customization points in a living style guide. Keep examples close to the implementation so they change together.
Exercise
Which technique gives a browser-enforced boundary around a reusable widget?
Show answer
Shadow DOM. CSS Modules isolate names during the build, while @scope limits selector reach.