Sub topic 3
Reusing Styles with CSS Modules
Assume you know React components, props, JSX, CSS selectors, ES module imports, and a bundler such as Vite, webpack, or Next.js.
Reusing Styles with `composes`
CSS Modules support composes for sharing declarations between local classes. The imported class includes both generated class names.
/* Button.module.css */
.base {
padding: 0.5rem 1rem;
border-radius: 4px;
}
.danger {
composes: base;
background: #b91c1c;
color: white;
}import styles from './Button.module.css';
export function DeleteButton() {
return <button className={styles.danger}>Delete</button>;
}Use composes for stable style relationships. For conditional combinations, a helper such as clsx is often clearer.
Targeting Unscoped Classes
CSS Modules scope local class names, but third-party widgets and legacy markup may use global names. Use :global only at that boundary.
.page :global(.legacy-widget) {
margin: 0;
}.page remains scoped. .legacy-widget remains unchanged, so this rule can match the external class.
Passing Dynamic Values
CSS Modules generate classes at build time. For values that change at runtime, use a CSS custom property.
.bar {
width: var(--progress);
height: 8px;
background: #16a34a;
}import type { CSSProperties } from 'react';
import styles from './Progress.module.css';
export function Progress({ value }: { value: number }) {
return (
<div
className={styles.bar}
style={{ '--progress': `${value}%` } as CSSProperties}
/>
);
}This keeps the structure in CSS while React supplies the changing value.
Tooling, Types, and Tests
Your framework must process .module.css files and expose class names as imports. Vite, webpack configurations, and Next.js support this pattern, but plain browser JavaScript does not.
TypeScript needs an ambient module declaration:
declare module '*.module.css' {
const classes: { readonly [key: string]: string };
export default classes;
}Jest must also map CSS imports to a mock, commonly with identity-obj-proxy, so styles.button behaves like a class name during tests. Test rendered behavior and accessible output, rather than generated class-name text.
Pitfalls and Organization
- Do not rely on generated class names. They can change between builds.
- Avoid unscoped element selectors such as
button { ... }in a module when the rule should affect only one component. - Keep component styles beside the component, and place truly shared module styles in a named shared directory.
- Use
composesfor CSS reuse, not to hide complicated component state.
Exercise
When should you use a CSS custom property instead of creating a class for every value?
Show answer
Use a custom property when the value changes at runtime, such as a progress percentage. Keep the fixed visual structure in the CSS Module.