Course contentsShow
← Web Development
Lesson 1344 of 2,98224. CSS Architecture and MaintainabilityFree lesson

Importing and Using Styles

Importing CSS Module files as JavaScript objects and applying scoped class names to elements in your markup.

Importing and Using Styles

What You'll Learn

You'll learn how to import CSS Module files as JavaScript objects and apply their scoped class names to your React or JavaScript markup.

The Core Idea

Once you've created a CSS Module file (like Button.module.css), you need to bring those styles into your JavaScript component. CSS Modules work by converting your class names into unique identifiers automatically. When you import a CSS Module, you're actually importing a JavaScript object where the keys are your original class names and the values are the generated, scoped class names.

How It Works

Import your CSS Module file using standard ES6 import syntax:

import styles from './Button.module.css';

The styles object now contains all your class names. If your CSS file defined .primary and .large, you'd access them as styles.primary and styles.large.

Apply these classes to your elements using JavaScript expressions:

<button className={styles.primary}>Click Me</button>

When this renders, the actual HTML might look like:

<button class="Button_primary__x7k2p">Click Me</button>

Notice how the scoped name prevents conflicts with other .primary classes elsewhere in your app.

Combining Multiple Classes

You can combine multiple CSS Module classes:

<button className={`${styles.primary} ${styles.large}`}>
  Big Button
</button>

Think of it like this: Instead of writing class names directly as strings, you're retrieving them from a JavaScript object that guarantees uniqueness—like getting a ticket number from a dispenser instead of choosing your own.

Key Takeaway: Import CSS Modules as JavaScript objects, then access scoped class names through that object using dot notation or bracket syntax, applying them to your elements' className attributes.