Sub topic 2
How Class Names Become Locally Scoped
Assume you know React components, JSX, CSS selectors, ES module imports, and a bundler such as Vite, webpack, or Next.js.
Generated Class Names
A CSS Module scopes class names during the build. A class declared as .button in Button.module.css does not reach the browser as the plain name button. The bundler replaces it with a generated name that includes the file and local class, such as Button_button__a1b2c.
The generated name is usually stable for the same source and build settings, but it is an implementation detail. Do not use it in tests, selectors, or application logic.
/* Button.module.css */
.button {
padding: 0.5rem 1rem;
border: 0;
border-radius: 4px;
}import styles from './Button.module.css';
export function Button({ children }) {
return <button className={styles.button}>{children}</button>;
}The import creates a styles object. Its button property contains the generated class name.
Naming and Access Syntax
Use camelCase for class names that you access with dot notation:
.cardHeader {
font-weight: 700;
}<h2 className={styles.cardHeader}>Account</h2>Names containing hyphens require bracket notation:
.card-header {
font-weight: 700;
}<h2 className={styles['card-header']}>Account</h2>Choose one naming style for a project. CamelCase usually produces simpler JSX.
Combining and Switching Classes
An element can receive multiple scoped classes. The clsx package conditionally joins class names and ignores false values.
import clsx from 'clsx';
import styles from './Button.module.css';
export function Button({
variant = 'primary',
disabled = false,
children,
}) {
return (
<button
className={clsx(styles.button, styles[variant], {
[styles.disabled]: disabled,
})}
disabled={disabled}
>
{children}
</button>
);
}Here, styles.button supplies shared layout, styles[variant] selects a variant such as primary, and styles.disabled adds state styling. Keep variant values constrained to keys that exist in the stylesheet. Otherwise, an invalid value produces an undefined class and missing styles.
Exercise
Why does styles.button work even though the browser receives a longer generated class name?
Show answer
The bundler creates an object that maps the local button key to the generated class name.