Skip to main content
Saved

Pattern Styling Beginner

CSS Modules & Scoped Styles

The build tool gives each component’s classes unique names, so styles from different components can’t conflict, and the work happens at build time.

Examples
React, Vue, Svelte and native web
Read
5 min

The problem

You might name a class .header, and then someone installs a component library that also has a .header class. Now the rules from both apply to each other’s elements.

The pattern

With CSS Modules, the build tool turns your readable class names into unique ones. When you write .button, it becomes .Button_button__a1b2c3 in the output, so two components can’t end up with the same class name.

Problem

I’ve debugged CSS issues where button padding changed because a developer on another team added a .button class in a completely different feature. With global CSS, any change can break something three pages away.

Teams usually deal with this using BEM naming, such as .component-name__element-name--modifier. That works, but it takes discipline. Developers on your team might forget the conventions or disagree about them, and your code reviews can turn into checking everyone’s class names. Even when everyone follows BEM, the class names get very long.

Solution

You import the styles as a JavaScript module, with import styles from './Button.module.css'. styles is an object where styles.button contains the generated class name, and you apply that class name to your elements.

Vue’s scoped styles work in a similar way, but they use data attributes instead of renamed classes. Svelte adds its own unique class, such as svelte-xyz123, to each element at compile time and limits the component’s rules to that class. In all three, a rule you write for .button in one component can’t match a .button in another.

CSS Modules only rename classes, though, so a rule like .card h2 still matches an h2 inside any child component, and inherited properties such as color and font-family still pass down to children. Vue and Svelte go further and only match elements in the component’s own template, so a rule doesn’t apply to the elements inside a child component, although in Vue it can still match the child’s root element. For the cases where you do want to style a child’s elements or write a global rule, Vue has :deep() and all three have :global().

Two related patterns isolate styles in other ways. With Shadow DOM, which Style Isolation covers, the browser itself keeps outside rules out of a web component and the component’s rules in. With CSS-in-JS, you write the styles in JavaScript and a library generates the class names, often at runtime.

Example

The first example styles the same Button, which takes a variant prop, in each framework, and the later ones cover composition, global rules, and theming.

Basic Scoped Styles

/* Button.module.css */
.button { padding: 10px; border-radius: 4px; }
.primary { background: blue; }
.secondary { background: gray; }
import styles from './Button.module.css';

function Button({ variant = 'primary', children }) {
  // styles.button and styles[variant] are the generated class names
  return (
    <button className={`${styles.button} ${styles[variant]}`}>
      {children}
    </button>
  );
}

Generated Output

A second component can use the class name .button for something that looks completely different.

/* Card.module.css */
.button { background: none; text-decoration: underline; }

This is roughly what the browser gets for the two components. The exact names depend on your build tool, but each one includes the file or component it came from, so the Card’s rule can’t match the Button’s element.

<!-- CSS Modules -->
<button class="Button_button__a1b2c3 Button_primary__d4e5f6">Save</button>
<button class="Card_button__g7h8i9">Details</button>

<!-- Vue scoped styles: the class stays, and an attribute is added -->
<button class="button primary" data-v-7ba5bd90>Save</button>

<!-- Svelte: an extra class is added -->
<button class="button primary svelte-xyz123">Save</button>
/* CSS Modules */
.Button_button__a1b2c3 { padding: 10px; border-radius: 4px; }
.Card_button__g7h8i9 { background: none; text-decoration: underline; }

/* Vue scoped styles */
.button[data-v-7ba5bd90] { padding: 10px; border-radius: 4px; }

/* Svelte */
.button.svelte-xyz123 { padding: 10px; border-radius: 4px; }

Composition

With scoped classes, you can’t rely on a shared global class, so CSS Modules add a keyword of their own, composes, which isn’t standard CSS, for sharing rules between files. When .button composes baseButton, styles.button contains both generated class names, so the element gets the shared rules and its own.

/* shared.module.css */
.baseButton { padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
/* Button.module.css */
.button {
  composes: baseButton from './shared.module.css';
  background: blue;
}

.iconButton {
  composes: baseButton from './shared.module.css';
  background: transparent;
}
import styles from './Button.module.css';

<button className={styles.button}>Primary</button>
<button className={styles.iconButton}>Icon</button>

Global Styles and Child Components

Sometimes a rule has to match something outside the component, such as body, a class from a third-party library, or an element that a child component renders. Each tool has a way to opt out of the scoping for one selector.

/* App.module.css */
/* :global() leaves the class name as it is */
:global(.legacy-class) { color: red; }

.container { padding: 20px; }
.container :global(.legacy-component) { margin: 10px; }

TypeScript Support

TypeScript can’t tell which class names a CSS file contains. A tool such as typed-css-modules can generate a declaration file next to each module that lists them, so a misspelled class name becomes a type error.

// Button.module.css.d.ts
declare const styles: {
  readonly button: string;
  readonly primary: string;
};
export default styles;
import styles from './Button.module.css';

<button className={styles.button}>Click</button>
<button className={styles.nonexistent}>Error</button> // TS error

Dynamic Classes with classnames

Once a Button has several optional classes, joining them in a template literal gets hard to read. The classnames package takes an object, and adds each key whose value is true.

import styles from './Button.module.css';
import classNames from 'classnames';

function Button({ variant, size, disabled, children }) {
  const buttonClass = classNames(styles.button, styles[variant], {
    [styles.large]: size === 'large',
    [styles.disabled]: disabled
  });
  return <button className={buttonClass}>{children}</button>;
}

Theming with CSS Variables

Class names are scoped, but CSS custom properties still inherit as usual. A theme class on a wrapper can set them, and the Button’s rule uses whichever values it inherits.

/* theme.module.css */
.light { --primary: blue; --bg: white; }
.dark { --primary: lightblue; --bg: #1a1a1a; }
/* Button.module.css */
.button { background: var(--primary); color: var(--bg); }
import theme from './theme.module.css';
import styles from './Button.module.css';

function App({ isDark }) {
  return (
    <div className={isDark ? theme.dark : theme.light}>
      <button className={styles.button}>Themed</button>
    </div>
  );
}

Build Tool Configuration

This step is optional. Vite, Next.js, and most other current tools treat any file ending in .module.css as a CSS module without any configuration. The options below are for a webpack setup you configure yourself, or for changing how the generated names look.

// webpack.config.js
module.exports = {
  module: {
    rules: [{
      test: /\.module\.css$/,
      use: ['style-loader', {
        loader: 'css-loader',
        options: { modules: { localIdentName: '[name]__[local]___[hash:base64:5]' } }
      }]
    }]
  }
};

// vite.config.js
export default {
  css: {
    modules: { localsConvention: 'camelCase', generateScopedName: '[name]__[local]___[hash:base64:5]' }
  }
};

Benefits

  • You and another developer can both use .header without breaking each other’s styles, because the generated names can’t conflict.
  • The build tool keeps styles isolated automatically, so your team doesn’t need to stick to a naming convention like BEM.
  • The class names are generated at build time, so if the CSS is extracted into its own file, the browser applies the styles without running any JavaScript. The webpack example above uses style-loader, which injects the styles with JavaScript and is common in development, and production builds usually extract the CSS with a plugin such as mini-css-extract-plugin.
  • It’s normal CSS syntax with automatic scoping, so apart from composes and :global(), there’s no new language to learn.
  • Moving or renaming a component is safer, because its styles are in a file that only that component imports.
  • Removing unused CSS is easier, because each component imports its styles explicitly, so you can find a CSS module that isn’t imported anywhere and delete it.
  • For global styles in third-party code or browser resets, :global() lets you opt out of the scoping.

Tradeoffs

  • The browser’s developer tools show generated names like Button_button__a1b2c3, which make it harder to find the rule in your source files without source maps.
  • To share styles, you have to compose them explicitly, because you can’t rely on global classes being available everywhere anymore.
  • Dynamic styles are harder, because CSS Modules are static, so values that change at runtime need CSS custom properties or inline styles.
  • You need a build tool such as Webpack or Vite, although most of them handle .module.css files without any configuration.
  • Third-party CSS frameworks such as Bootstrap ship global classes, so overriding them from a CSS module needs :global() wrappers.
  • Component libraries such as Material UI are styled with CSS-in-JS, using Emotion by default, so you usually override their styles through their own theming and sx APIs instead.
  • Combining several classes on one element is verbose and needs a template literal or a helper such as classnames.
  • TypeScript support needs type definitions for your CSS modules, which you either generate or write manually.

Summary

CSS Modules generate unique class names, so the styles in one component can’t clash with the styles in another. You write plain CSS, import it into the component, and the build tool makes sure those class names only match that component’s elements, so you can use everything CSS offers without breaking styles somewhere else in the app.

See also

Next pattern Debounce Debouncing delays a function call until events have stopped for a short time, so a burst of rapid calls becomes a single call.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.