CSS Modules

CSS Modules

Using 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:

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

Card.jsx

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

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.

<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>
._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.

Last updated