Sub topic 15
Common Pitfalls and Organizing Styles
This chapter assumes you can create a .module.css file, import it as styles, combine classes with clsx, and use composes and :global. It collects the mistakes that show up most often in real projects and then describes a file layout that keeps them from recurring.
Pitfall: Unscoped element selectors
CSS Modules only rewrite class names (and ids, keyframe names, and a few other identifiers). A selector made only of an element name is left alone and stays global.
/* Card.module.css */
p {
margin: 0;
color: #374151;
}
.title {
font-weight: 600;
}The .title rule is scoped. The p rule is not. It applies to every paragraph on the page once this file is loaded, including paragraphs in components that never import Card.module.css. Many build tools also reject such files in "pure" mode, which requires every selector to contain at least one local class.
The fix is to anchor the element selector to a local class:
.card p {
margin: 0;
color: #374151;
}Now the rule only matches paragraphs inside an element that has the generated .card class. A better option is often to give the paragraph its own class (.body) so the rule does not depend on the markup structure.
Pitfall: Relying on generated class names
The generated names look like Button_primary__3xK9a or _primary_1a2b3, depending on your tool's settings. They change between builds, between development and production, and when you rename a file.
Do not use them in:
- Test selectors such as
document.querySelector('.Button_primary__3xK9a'). - Snapshot tests that record the full class string.
- End-to-end tests that look up elements by class.
- Documentation or analytics code that expects a stable name.
Use accessible roles and text in tests (getByRole('button', { name: 'Save' })), or add a data-testid attribute when no role fits. If you must assert that a class was applied, compare against the styles object, not a literal string:
import styles from './Button.module.css';
expect(screen.getByRole('button')).toHaveClass(styles.primary);This stays correct whatever name the build produces.
Pitfall: Missing keys and `undefined` classes
The styles object is a plain JavaScript object. If you ask for a key that does not exist in the CSS file, you get undefined, and no error is raised.
// Button.module.css has .button and .primary, but no .primry
<button className={styles.primry}>Save</button>React renders class="undefined" or no class at all, depending on how the value is joined. The same problem occurs with dynamic lookup, as in styles[variant], when variant has a value with no matching class.
Ways to catch this:
- Use TypeScript with generated typings (for example
typed-css-modulesor a bundler plugin that emits.d.tsfiles). Misspelled keys then fail at compile time. The genericdeclare module '*.module.css'declaration from the previous chapter accepts any key, so it does not catch typos. - Restrict the
variantprop to a union type such as'primary' | 'secondary'. - Keep variant names in the component and class names in the CSS file in exact agreement, and add a test that renders every variant.
Pitfall: Hyphenated class names
A class named .primary-button is imported as the key 'primary-button'. Dot access (styles.primary-button) is parsed as a subtraction and fails. Either write styles['primary-button'] or use camelCase in the CSS file (.primaryButton) so that styles.primaryButton works. Pick one convention for the project and apply it everywhere. Some tools offer a localsConvention option (camelCase or camelCaseOnly in css-loader) that exposes both forms. This is convenient, but it means a key can exist in two spellings, so settle on one in code review.
Pitfall: Specificity and ordering between modules
Scoping removes name collisions. It does not remove the cascade. Two modules can still style the same element, and then the rule that wins depends on specificity and on the order in which the CSS is loaded.
A common case: a parent passes a className to a child so it can adjust spacing.
<Button className={styles.wide}>Save</Button>Both .wide (from the parent's module) and .button (from the child's module) have the same specificity. The winner is whichever stylesheet appears later in the final bundle, and that order can differ between development and production builds, or change when you reorder imports.
Safer approaches, from most to least preferred:
- Expose an explicit prop on the child (
size="wide") and let the child own all of its own styles. - Let the parent style only its own wrapper element and position the child there.
- If the parent must override the child, raise specificity deliberately (
.parent .wide), or use CSS cascade layers (@layer) so the order is explicit rather than accidental.
Pitfall: `composes` limits
composes works only on a single class selector. These do not work:
/* Not allowed */
.danger:hover {
composes: base;
}
.card .danger {
composes: base;
}Also, composes does not copy declarations. It adds the other class name to the exported value, so the element gets both classes and the cascade decides the winner. If .danger sets padding and .base also sets it, the result depends on which rule comes later in the bundle. Keep composed base classes free of properties that the composing class overrides, or avoid the overlap.
Pitfall: Overusing `:global`
:global is for a narrow job: targeting class names you do not control, such as markup rendered by a third-party widget. Each use is a hole in the scope.
.page :global(.legacy-widget) {
margin: 0;
}Notice that the rule is anchored to a local class (.page). Without that anchor, the rule would apply everywhere. Avoid the bare form :global .legacy-widget { ... } and avoid :global on a whole block unless the file is truly meant to be global.
Pitfall: Dynamic values and inline styles
Do not generate a new class for every runtime value. Pass the value through a custom property and read it in the stylesheet, as shown earlier with --progress. Keep the property name in one place and document it at the top of the CSS file, because the link between the component and the stylesheet is a string and nothing checks it.
Pitfall: Global side effects in tests and tools
Jest does not process CSS. Without configuration, importing a .module.css file throws a syntax error. Map module files to identity-obj-proxy so that styles.button returns 'button':
// jest.config.js
module.exports = {
moduleNameMapper: {
'\\.module\\.css$': 'identity-obj-proxy',
},
};With this mapping, styles[variant] returns the variant name itself, so a misspelled key will not fail the test. Combine it with TypeScript typings or a per-variant render test to keep that safety net.
Organizing styles in a project
Pitfalls are easier to avoid when the file layout makes the rules obvious.
Colocate each module with its component
src/
components/
Button/
Button.jsx
Button.module.css
Button.test.jsx
index.js
Card/
Card.jsx
Card.module.css
styles/
reset.css
tokens.css
utilities.cssOne module per component keeps the styles easy to find and delete. When a component is removed, its styles go with it.
Share values, not selectors
Put design tokens (colors, spacing, font sizes) in custom properties in a global file such as tokens.css:
:root {
--color-primary: #2563eb;
--color-primary-hover: #1d4ed8;
--space-2: 0.5rem;
--space-4: 1rem;
}Modules then read tokens with var(--color-primary). Custom properties inherit through the DOM, so they cross module boundaries without needing :global. If you also use a preprocessor, you can share variables and mixins through @use instead.
Rules of thumb
| Situation | Recommended approach |
|---|---|
| Variants of one component | Separate classes in the same module, combined with `clsx` |
| Same base look in several classes | `composes` within a file, or a shared base class |
| Style shared by two unrelated components | Extract a new component, or use `composes: x from './shared.module.css'` |
| Design tokens | Custom properties in a global stylesheet |
| Runtime values | Custom property set through the `style` prop |
| Third-party markup | `:global` anchored to a local class |
| Page-wide defaults | Plain global stylesheet, loaded once at the root |
Keep modules small and flat
- Prefer single-class selectors. Deep nesting such as
.card .header .title spancouples the CSS to the markup and raises specificity. - Name classes by role (
.title,.footer), not by appearance (.blueText). - Do not share one large module across many components. It brings back the global-stylesheet problem inside a single file, and unused rules cannot be safely removed.
- Add a linter such as Stylelint with
stylelint-config-css-modulesso that:global,composes, and:exportdo not produce false errors.
Checklist before merging
- Every selector contains at least one local class.
- No test, snapshot, or script depends on a generated class name.
- Every key read from
stylesexists, and variant names are typed. composesis used only on single class selectors and does not overlap properties with its base.- Each
:globalis anchored to a local class and has a comment explaining why. - Shared values live in custom properties, not in copied declarations.
Exercise
A teammate adds a { text-decoration: none; } to Nav.module.css and finds that links in an unrelated Footer component lost their underlines. Why did this happen, and how would you fix it?
Show answer
Element selectors are not rewritten by CSS Modules, so a { ... } is a global rule that applies to every anchor on the page once Nav.module.css is loaded. Fix it by anchoring the rule to a local class, for example .nav a { text-decoration: none; }, or by giving the links their own class such as .link. Global element defaults belong in a plain global stylesheet.
Exercise
A component uses className={styles[variant]}. After a refactor, one page renders buttons with no styling and no error appears. List two ways to catch this earlier.
Show answer
The variant value had no matching class, so styles[variant] was undefined. Type the variant prop as a union of known names and use generated typings so that unknown keys fail to compile. Alternatively, add a test that renders every variant and asserts toHaveClass(styles.primary) style checks, which fail if the key is missing. Mapping CSS to identity-obj-proxy alone will not catch it.