CSS Modules
- There is a problem with vanilla CSS, if we have another stylesheet which contains CSS class with the same name defined in component CSS, we're going to run into clashes.
- CSS modules try to solve name clashes.
- A CSS module is a CSS file in which all class names are scoped locally, just like a JavaScript module. So they allow us to use the same CSS class name in different files without worrying about name clashes.
- The CSS inside a module is available only for the component that imported it.
- CSS modules resolve name conflicts issue by generating unique class names during the build process.
Usage
- Create the CSS module with the
.module.css
. Follow camelCase notation
ListGroup.module.css
.listGroup {
border: 2px solid lightblue;
}
- Import CSS module in the component. All the CSS rules are available as properties in styles object
ListGroup.tsx
import styles from "./ListGroup.module.css";
//with camecase class name
<ul className={styles.listGroup}>
//with kebabcase class name
<ul className={styels["list-group"]}>
Multiple classes
<ul className={["container", styles.listGroup].join(" ")}>