CodeBlanks Logo Icon CodeBlanks

CSS Modules

Learn to create local class names with CSS Modules.

CSS Modules

CSS Modules scope styles to a component. The file is named Button.module.css; on import you get an object: import styles from "./Button.module.css".

You apply a class with className={styles.btn}. The bundler generates a unique name for each class, so there is no clash.

This method is the standard way to write safe styles in big projects.

Scoped class names

Modules turns a simple name like .btn into a unique name like Button_btn__x7y2. You do not write this name; the bundler generates it.

So even if two components both have .btn, they do not clash. This is the basis of scalable styling.

You can use camelCase class names: styles.primaryBtn.

Practice Modules button

Complete the skeleton. Write a PrimaryButton component; import the styles object from "./PrimaryButton.module.css". Return <button className={styles.primary}>Send</button>. Export it.

Starter code

App.jsx
// Define PrimaryButton here

// remember to import styles

Sample solution

App.jsx
import styles from "./PrimaryButton.module.css";

function PrimaryButton() {
  return <button className={styles.primary}>Send</button>;
}

export default PrimaryButton;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How does a CSS Modules file name end?

App.jsx
The bundler scopes based on the suffix.
  • .css
  • .style
  • .scss
  • .module.css Correct answer

Explanation: The .module.css suffix marks it as a module.

2 CSS Modules: fill in the missing part

Question
className={____}
Answer
className={styles.btn}

Explanation: You took the class from the styles object.

3 CSS Modules: match the terms

Term Meaning
.module.css Modules suffix
styles.btn Class usage
unique name No clash
camelCase Naming

All lessons in Beginner