HTML & CSS
/Advanced
CSS Modules
Definition
A CSS file in which all class names and animation names are scoped locally by default.
Explain Like I'm New
The ultimate solution to CSS conflicts in React/Next.js. If you write `.button { color: red; }` in a CSS Module, the compiler automatically renames your class to something insane like `.Button_button__3xyz`. Because the name is random, it is impossible for it to conflict with another button on your site.
Real World Example
Used natively in Next.js. You create a file named `Button.module.css`, and import it directly into your React component. You get the power of vanilla CSS with the safety of scoped styles.
Common Use Cases
- •React/Next.js applications
- •Preventing global CSS bleed
Interactive Example
/* Note: This is a conceptual example of how CSS Modules work in React. It requires a build step to function. */ /* File: Card.module.css */ /* .container { background: white; border-radius: 8px; } .title { color: blue; } */ /* File: Card.jsx */ /* import styles from './Card.module.css'; export default function Card() { // The bundler turns 'styles.container' into an ugly, unique string! return ( <div className={styles.container}> <h2 className={styles.title}>Hello World</h2> </div> ); } */ /* HTML Output in the Browser: */ <div class="Card_container__2x8z9"> <h2 class="Card_title__9a2b1">Hello World</h2> </div>
Interview Questions
basic
- What problem do CSS Modules solve perfectly?
intermediate
- Do you write regular CSS syntax inside a CSS Module file?