> For the complete documentation index, see [llms.txt](https://ga0-2.gitbook.io/seifxr10anz-content/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ga0-2.gitbook.io/seifxr10anz-content/week-21/day-2-styling-react/css-modules.md).

# CSS Modules

## CSS Modules

Using [CSS Modules](https://github.com/css-modules/css-modules) in React lets us scope our CSS styles to a single component preventing clashes with other styles in our application.

To use CSS Modules in components the css file must follow this naming convention: `[name].module.css`, with `name` typically being the component name.

**Example Card Component w/ CSS Modules**

*Card.module.css*

Style normally using CSS classes:

```css
.card {…}
.cardImage {…}
.cardTitle {…}
.cardBody {…}
.cardBody p {…}
```

*Card.jsx*

Import the class names as `styles` and apply to the JSX elements.

```jsx
import styles from "./Card.module.js"

const Card = () => {
  return (
    <section className={styles.card}>
      <img className={styles.cardImage} />
      <h4 className={styles.cardTitle}>…</h4>
      <div className={styles.cardBody}>
        <p>…</p>
      </div>
    </section>
  );
};
```

After compilation (built-in to Vite), unique class names will be generated and applied to the HTML and CSS.

```html
<section class="_card_d0rv0_1">
  <img class="_cardImage_d0rv0_10">
  <h4 class="_cardTitle_d0rv0_16">…</h4>
  <div class="_cardBody_d0rv0_20">
    <p>…</p>
  </div>
</section>
```

```css
._card_d0rv0_1 {…}
._cardImage_d0rv0_10 {…}
._cardTitle_d0rv0_16 {…}
._cardBody_d0rv0_20 {…}
._cardBody_d0rv0_20 p {…}
```

This improves encapsulation and makes it easier to maintain and style components especially in bigger applications.
