What You'll Learn
You'll learn how to reuse CSS Module styles across classes using the composes keyword, eliminating duplication and ensuring design consistency.
The Problem with Duplication
When building components, you often need styles that share common properties. Without composition, you'd copy-paste or apply multiple classes to every element, leading to bloated stylesheets and maintenance headaches.
The composes Keyword
CSS Modules provide a special composes keyword that lets one class inherit styles from another—like extending a base class in programming. This happens at build time, not runtime.
Basic syntax:
/* Button.module.css */
.base {
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
}
.primary {
composes: base;
background-color: blue;
color: white;
}
.secondary {
composes: base;
background-color: gray;
color: black;
}
In your component:
import styles from './Button.module.css';
function Button({ variant }) {
return (
<button className={variant === 'primary' ? styles.primary : styles.secondary}>
Click me
</button>
);
}
The .primary class automatically includes all .base styles plus its own. You don't need className={{styles.primary}}—composition handles it.
Composing from Other Files
You can even compose from external modules:
.button {
composes: base from './common.module.css';
font-weight: bold;
}
This promotes true style reusability across your component library.
Analogy: Style Inheritance
Think of composes like inheriting from a parent component in React—the child gets all parent behavior automatically, then adds its own specialization.
Key Takeaway: Use composes in CSS Modules to build layered, reusable styles without class name juggling or duplication—keeping your styles DRY and maintainable.