CSS Module patterns
CSS module overview
A CSS module is a regular stylesheet (CSS file) whose classes are subject to processing.
A processor parses classes in the stylesheet (such as superGreat) and derive unique names (such as superGreat_1kmox6oL39). It then produces a derived stylesheet using the unique class names:
.superGreat_1kmox6oL39 {
} /* post-processing */
the class map object
Since the developer only knows about the pre-processed class names (such as superGreat), the processor creates a JS object mapping the class names to their post-processed name (a class map object). The developer only interacts with this map. We often call it classes:
<div className={classes.superGreat}></div> // class="superGreat_1kmox6oL3"
When using a bundler that supports CSS modules, we import the map directly from the CSS module path:
import classes from "xxx.module.css"
Note: We avoid hyphens in class names, because it forces the use of raw strings in property lookups:
<div className={classes["super-great"]}></div> // superGreat_1kmox6oL3
Mantine patterns with CSS modules
targeting inner elements directly
In one CSS module, we target the inner-elements of a single Mantine component (virtually creating a variant of this component).
module name
As the module defines style for a custom variant, we name the module accordingly, e.g.: PrimaryButton.module.css.
name classes according to inner elements
We name classes according to the inner-element they target, such as root or label:
/* PrimaryButton.module.css */
.root {
}
.root:hover {
}
.label {
}
We then attach classes to the inner slots of classNames:
<Button
classNames={{
root: classes.root,
label: classes.label,
}}
>
Since the class map fields already take the name of the inner-elements, they cleanly match the API expected by classNames: as such, we provide the class map itself to classNames:
{/* cleaner */}
<Button classNames={classes}>