Q1. What are CSS Modules?
CSS Modules are CSS files where class names are scoped locally by default.
When imported, they generate unique class names, preventing conflicts.
In React, you can use CSS Modules by naming the file
When imported, they generate unique class names, preventing conflicts.
In React, you can use CSS Modules by naming the file
styles.module.css and importing as styles.Q2. How do you use CSS Modules in a React component?
Create a file like
In the component, import styles from './Button.module.css'.
Then use
The generated class name will be unique.
Button.module.css with .btn { ... }.In the component, import styles from './Button.module.css'.
Then use
className={styles.btn}.The generated class name will be unique.
Q3. What are the benefits of CSS Modules?
They avoid global scope collisions, make styles component-specific, and encourage modular design.
They also support composition and can be used with preprocessors.
They also support composition and can be used with preprocessors.
Q4. Can you use multiple classes with CSS Modules?
Yes, you can combine classes using template literals:
Or use a library like
className={`${styles.btn} ${styles.primary}`}.Or use a library like
classnames for conditional classes.Q5. How do CSS Modules differ from regular CSS?
Regular CSS has global scope; CSS Modules are scoped locally by default.
In regular CSS, you need to follow naming conventions like BEM to avoid conflicts; CSS Modules handle this automatically.
In regular CSS, you need to follow naming conventions like BEM to avoid conflicts; CSS Modules handle this automatically.
