CSS Modules
Subject: React
CSS Modules in React β Full Explanation
π What Are CSS Modules?
CSS Modules let you write regular CSS, but the styles are scoped locally to the component theyβre used in. This means:
- β Class names are automatically made unique
- β Styles donβt leak or conflict with other components
π Think of CSS Modules as private styling for each component.
π― Why Use CSS Modules?
Global CSS Problem | CSS Modules Fix |
---|---|
Class name collisions | Automatically generates unique class names |
Global styles override others | Styles stay local to the component |
Hard to manage in big apps | Styles live near components |
π¦ File Naming Convention
The .module.css
extension tells React to treat it as a CSS Module.
β Step-by-Step Example
πΉ Step 1: Create Component and CSS Module
π§ File: Button.module.css
π§ File: Button.jsx
π What Happens Internally?
React compiles your class name into something like:
β So no two components will ever accidentally share the same styles.
π Dynamic Class Names
Combine multiple classes:
Or use the classnames
package:
π§ Key Benefits of CSS Modules
Benefit | Description |
---|---|
Local scoping | Class names are unique to the file/component |
Easy maintenance | No accidental overrides from other components |
Tool-friendly | Works with CSS preprocessors like .scss |
CRA/Vite support | Built-in support in most React setups |
β οΈ Notes & Best Practices
β
Use camelCase or hyphen-case in .module.css
files
β Donβt use global selectors like body
, *
, html
inside modules
π Keep CSS files close to the component they style
π§ͺ Final Real-World Example
π§ Card.module.css
π§ Card.jsx
π Summary Table
Feature | Description |
---|---|
.module.css | File naming convention for CSS Modules |
import styles from | Imports styles as a scoped object |
styles.className | Use like styles.btn to apply the class |
Prevents conflicts | All class names are unique and scoped automatically |
Component-based apps | Keeps styles organized and reusable per component |
Advertisement Slot 1
Advertisement Slot 2