Sub topic 10
Using :global to target unscoped classes
This chapter assumes you can create and import a .module.css file, apply classes through the styles object, and read basic CSS selectors and specificity. It covers :global, the escape hatch from local scoping.
Why you sometimes need to leave the scope
CSS Modules rewrite every class selector in a .module.css file into a unique generated name. That is what protects your components from collisions. It also means you cannot write a selector for a class name you did not define in that file.
Some class names come from outside your module:
- A third-party widget, such as a date picker or a chart, adds its own classes to the DOM.
- Legacy markup or a CMS outputs plain class names like
legacy-widget. - A library adds state classes to
<body>or<html>, such asmodal-open. - Server-rendered HTML contains classes you do not control.
If you write .legacy-widget { margin: 0; } in a module, the build tool renames it to something like Page_legacy-widget__x7Qa2. The rule then matches nothing, because the real element still carries the plain class legacy-widget. The :global pseudo-class tells the build tool to leave a selector alone.
How :global works
:global is not a real browser pseudo-class. The CSS Modules processor (in most setups, postcss-modules or the css-loader implementation) removes it at build time and skips renaming whatever it wraps. The browser never sees it.
There are two forms.
Function form
:global(...) marks only the selector inside the parentheses as global. Everything else in the selector stays local.
.page :global(.legacy-widget) {
margin: 0;
}After the build, the output looks like this:
.Page_page__a1B2c .legacy-widget {
margin: 0;
}The .page part is renamed. The .legacy-widget part is untouched. The rule matches a .legacy-widget element only when it is inside your component's .page element.
Switch form
:global without parentheses switches the rest of the selector to global mode. Everything to its right is left unscoped.
:global .legacy-widget .legacy-title {
font-weight: 600;
}Here both .legacy-widget and .legacy-title stay as written. You can switch back with :local:
.page :global .legacy-widget :local .highlight {
color: #b45309;
}In this rule, .page and .highlight are scoped, while .legacy-widget is not. The function form is easier to read and harder to get wrong, so prefer it. Use the switch form only when a long chain of external class names makes parentheses noisy.
A complete example
Suppose a page embeds a third-party rich text editor that renders markup with the classes editor and editor-toolbar. You want to adjust the toolbar spacing only on this page.
/* Article.module.css */
.article {
max-width: 48rem;
margin: 0 auto;
}
.article :global(.editor-toolbar) {
gap: 0.25rem;
padding: 0.5rem;
}
.article :global(.editor) {
min-height: 12rem;
}import styles from './Article.module.css';
import { RichEditor } from 'some-editor-library';
export function Article() {
return (
<section className={styles.article}>
<RichEditor />
</section>
);
}The .article class is local and unique to this component. The editor's classes are global. Because every global selector sits under .article, the overrides apply only inside this component. Other pages that use the same editor are not affected.
This pattern is the most important one in the chapter: anchor a global selector to a local class. The local class gives the rule a boundary.
Global rules that are not anchored
You can write a fully global rule by wrapping the whole selector:
:global(body.modal-open) {
overflow: hidden;
}This is sometimes legitimate. A component that opens a modal might need to lock scrolling on <body>, and body is outside the component. But an unanchored global rule removes the protection CSS Modules gave you, because it affects the whole document. Anyone reading a different component will not expect this file to change body.
A safer way to handle the modal case is to toggle a class from JavaScript and keep the CSS where it belongs. Even then, a global rule is needed, because the class lands on <body>:
import { useEffect } from 'react';
export function useScrollLock(locked) {
useEffect(() => {
if (!locked) return undefined;
document.body.classList.add('modal-open');
return () => document.body.classList.remove('modal-open');
}, [locked]);
}/* Modal.module.css */
:global(body.modal-open) {
overflow: hidden;
}Keep this kind of rule next to the code that adds the class, and name it clearly so the connection is obvious.
Defining a global class that others can use
:global also works for defining a class, not only for targeting one. This is occasionally useful when you want to expose a stable class name that other code, such as a test or an analytics script, can rely on:
.card :global(.is-selected) {
outline: 2px solid #2563eb;
}import clsx from 'clsx';
import styles from './Card.module.css';
export function Card({ selected, children }) {
return (
<div className={clsx(styles.card, selected && 'is-selected')}>
{children}
</div>
);
}Note that the string 'is-selected' is passed directly, not read from styles. It has no generated name, so the :global selector matches it. Use this sparingly. It reintroduces a shared name, and two components could both define .is-selected with different meanings.
Common errors
Writing a plain selector for an external class
/* Does not work: .legacy-widget is renamed */
.page .legacy-widget {
margin: 0;
}This is the most common mistake. The rule compiles without errors and silently matches nothing. The fix is .page :global(.legacy-widget).
Forgetting the anchor
/* Risky: affects every .legacy-widget in the app */
:global(.legacy-widget) {
margin: 0;
}This works, but it changes every instance in the application. Add a local parent class unless you truly want that.
Expecting `styles` to expose global names
A class used only inside :global(...) is not added to the styles object. Both of these give undefined:
import styles from './Article.module.css';
console.log(styles['editor-toolbar']); // undefined
console.log(styles.editorToolbar); // undefinedYou never need to reference a global class through styles. It is already a plain string in the DOM.
Specificity surprises
A global selector under a local class has the specificity of two classes. If the third-party library styles its elements with a more specific selector, such as .editor .editor-toolbar button, your rule loses. Raise specificity by matching its structure, not by reaching for !important:
.article :global(.editor .editor-toolbar button) {
padding: 0.25rem 0.5rem;
}Use !important only when a library sets inline styles that no selector can beat.
Load order
Rules from different CSS files are ordered by the order the bundler includes them. If a library's stylesheet loads after yours and has equal specificity, it wins. Import the library's CSS before your component's module in the entry file, or increase specificity as shown above.
When not to use :global
:global is the right tool when the class name is outside your control. It is the wrong tool in these cases:
- You own the markup. Add a local class and use
styles.name. Do not give your own elements global class names just to style them. - You want shared design tokens. Use CSS custom properties defined on
:root, orcomposesfor reusing local styles. - You want site-wide resets or base styles. Put them in a normal
.cssfile (not.module.css) imported once at the app root. A global stylesheet is clearer than a module full of:globalrules.
| Situation | Approach |
|---|---|
| Override a third-party widget inside one component | `.local :global(.lib-class)` |
| Style an element you render yourself | Local class and `styles.name` |
| Toggle a class on `<body>` or `<html>` | `:global(body.some-class)` beside the code that sets it |
| Reset or typography for the whole app | A plain `.css` file imported at the root |
| Reuse a local style in another class | `composes` |
Wrapping a library once
If several components need the same overrides, avoid repeating :global rules. Wrap the library in one component and put all its overrides in one module:
import { RichEditor } from 'some-editor-library';
import styles from './StyledEditor.module.css';
export function StyledEditor(props) {
return (
<div className={styles.root}>
<RichEditor {...props} />
</div>
);
}/* StyledEditor.module.css */
.root :global(.editor) {
min-height: 12rem;
}
.root :global(.editor-toolbar) {
gap: 0.25rem;
}Now every page that needs the editor imports StyledEditor. The global selectors live in one file, under one local anchor, and are easy to find when the library changes its markup.
Exercises
Exercise
A module contains .panel .calendar-day { color: red; }, where calendar-day is a class added by a third-party calendar. The rule has no effect. Why, and how do you fix it?
Show answer
The build tool renames .calendar-day to a generated name, so the selector no longer matches the library's plain calendar-day class. Wrap it in :global: .panel :global(.calendar-day) { color: red; }. The local .panel still scopes the rule to this component.
Exercise
Given .page :global .a :local .b { }, which of the classes .page, .a and .b are renamed by the build?
Show answer
.page and .b are renamed because they are local. .a is left as written because it comes after the bare :global switch and before :local switches the mode back.
Exercise
Why does styles['editor-toolbar'] return undefined when editor-toolbar appears only inside :global(...) in the module?
Show answer
The styles object contains only local classes that the build tool renamed. A class wrapped in :global keeps its original name and is not exported, and the DOM already has it as a plain string.