Global Styles in CSS Modules
When working with CSS modules, there are times global classes need to be styled. The :global
operator does just that.
To target a single class, it can be passed as an argument to the operator:
:global(.class_name) {
// CSS Rules for ".class_name"
}
This can be nested in a module class to only apply it to elements with the global class within the module e.g.:
File:
MyComponent.module.scss
.my_component {
// Module rules
:global(.class_name) {
// These rules will be under:
// ".MyComponent_my_component__##### .class_name"
}
}
Further to this, module classes can also be nested within the global class:
File:
MyComponent.module.scss
.my_component {
// Module rules
:global(.class_name) {
// These rules will be under:
// ".MyComponent_my_component__##### .class_name"
.my_component_element {
// These rules will be under:
// ".MyComponent_my_component__##### .class_name .MyComponent_my_component_element__#####"
}
}
}
Multiple Classes
If there are multiple classes that need to be tarted, a :global
block can be used:
:global {
.this_class_is_global {
// Some rules for ".this_class_is_global"
}
.this_class_is_also_global {
// Some rules for ".this_class_is_also_global"
}
}
When using sass
, this also can be used to import another file, for example to qualify a libraries classes under a module
File:
MyComponent.module.scss
@use "sass:meta";
.my_component {
:global {
// This will qualify all imported styles as:
// ".MyComponent_my_component_##### {library classes / selectors}"
@include meta.load-css("library/styles/file");
}
}