Lesson 42 of 50
cssCSS Modules (Scoped CSS)
8 mins
Course progress84%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 42 of 50
css8 mins
Keep these ideas in mind as you work through the lesson.
CSS Modules is a build‑time technique that scopes class names to a component, preventing global leakage.
.module.css file with local class names.// Button.module.css
.primary {
background:#0066cc; color:#fff; padding:0.5rem 1rem; border:none;
}
import styles from './Button.module.css';
function Button({children}) {
return <button className={styles.primary}>{children}</button>;
}
Rendered HTML →
<button class="Button_primary__3X1yZ">…</button>
module.exports = {
module: {
rules: [
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: { modules: true }
}
]
}
]
}
};
styled-components for dynamic values).classnames library) or template literals.tokens.js) and import them into the component to keep colours consistent across CSS Modules and JS style objects.Because CSS Modules are just a naming convention, all accessibility considerations (focus styles, contrast) remain the same – just make sure you don’t unintentionally hide a globally‑scoped rule.