Course contentsShow
← Web Development
Lesson 1345 of 2,98224. CSS Architecture and MaintainabilityFree lesson

Composing Classes

Using the composes keyword to inherit styles from other classes within the same file or from external modules.

Composing Classes

You'll learn how to reuse and extend styles across multiple classes using CSS Modules' composes keyword.

What Is Class Composition?

Think of class composition like inheritance in programming, but for styles. Instead of copying and pasting common styles across multiple classes, you can have one class "inherit" or "compose" the styles from another. This keeps your CSS DRY (Don't Repeat Yourself) and makes maintenance much easier.

In CSS Modules, the composes keyword lets you pull in styles from other classes—either from the same file or from external modules—without duplicating code.

How It Works

When you use composes, the generated class names in the HTML will include both the composing class and the composed class. The styles cascade naturally, so the composing class can override specific properties while inheriting the rest.

/* button.module.css */
.base {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.primary {
  composes: base;
  background-color: blue;
  color: white;
}

.secondary {
  composes: base;
  background-color: gray;
  color: white;
}

You can also compose from external modules:

.myButton {
  composes: button from './common.module.css';
  margin-top: 20px;
}

This approach keeps your component styles focused on what's unique while reusing foundational styles effortlessly.

Key Takeaway: The composes keyword in CSS Modules lets you build classes by inheriting styles from other classes, promoting code reuse and reducing duplication across your stylesheets.