Logo with initials
Click me x5 ↓

Global/external classes in CSS Modules

CSS modules are scoped to their own files. This has 2 limitations:

  1. A plugin or a markdown processor adds an external class to one of your HTML elements, and you want to target it within a CSS module.
  2. You want to modify a rule when an external prefix has been added (with a dark mode, for example).

Here’s what you have to do:

Global/External class

CSS Modules gives you the :global prefix to allow you to target selectors that were created outside the module.

.navigation {
  :global {
    a.active {
      font-weight: 450;
    }
  }
}

In the example above, the active class will remain as active during compilation, whereas my .navigation class will be turned into a scoped, unique name like .navigation__2yrn8.

Internal prefix

You can also face the opposite problem. You want to modify the rules created in your CSS module when a prefix is present.

This is commonplace when implementing a “dark mode”, and a dark prefix/class is added to the HTML document.

In this case, you’ll also use the global selector, but a bit differently.

:global(.dark) .navigation {
  border: 1px solid rgba(255, 255, 255, 0.7);
}

In the example above, you modify the rules defined within your module when they are preceded by an external dark class.

Share