Modular CSS
Learn modular CSS writing methods.
What is modular CSS?
Modular CSS is the idea of splitting styles into small, component-based files. Each component owns its styles in its own file and does not leak into others. This lets large teams work the same codebase without clashes.
Three common methods exist: naming methods like BEM, the CSS Modules feature of build tools, and scoped styles in component frameworks. All three solve the same concern: stopping class names from clashing elsewhere by surprise.
How CSS Modules work
In a button.module.css file you write .root { ... }. At build time the tool renames this to a unique name like ._root_1a2b3. On the JavaScript side you read the name through styles.root and pass it as className={styles.root}.
The win: you can reuse the same .root name in another file; no clash because the compiled name differs. Class names stay short and meaningful while clash worry drops to zero in big projects.
Scoped styles in component frameworks
Some component frameworks — Vue, Svelte — offer a <style scoped> block inside the file. Styles you write here apply only to that component's elements; the tool adds a data attribute to the component's elements and ties the styles to that attribute.
The win is keeping component styles next to the component without opening a new file. One concern: scoped styles can rise to high specificity because each selector is combined with an attribute selector. Keep scoped styles short and within component boundaries.
Exercise Mark a global class
Write a .btn class with a padding: 0.5rem 1rem declaration. Right after, write a :global(.link) declaration with a color: navy declaration inside. Both class names start with a dot.
Show example solution
/* add the .btn class and the :global(.link) declaration */
.btn {
padding: 0.5rem 1rem;
}
:global(.link) {
color: navy;
}
Test yourself
-
Which method makes class names unique per file?
- Plain CSS files
- A single style.css
- CSS Modules
- The @import statement
Show answer
CSS Modules — Correct. CSS Modules renames each file's class names with unique suffixes at build time.
-
Define a class in a CSS Modules file
/* button.module.css file */ ____ { background: navy; color: white; }Show answer
/* button.module.css file */ .root { background: navy; color: white; } -
Match each modular CSS method to its feature
- BEM
- Naming method
- CSS Modules
- Build tool feature
- <style scoped>
- Component framework
- @import
- File merging