Search code examples
cssreactjsnext.jscss-modules

How to override global CSS in a CSS module file?


Lets say in my global.css file of a Next.js project I have:

.flex {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}

I also have a Layout.js component and a Layout.module.css file. The component looks like this:

import styles from "../styles/Layout.module.css";
const Layout = ({ children }) => {
  return (
    <div>
      <div className={styles.navbar}>
        <div className="flex">
        <h1>Structured Safety</h1>
        <nav>
            <ul>
                <li> <a href="#">Home</a> </li>
                <li> <a href="#">Demo</a> </li>
            </ul>
        </nav>
        </div>
      </div>
    </div>
  );
};

export default Layout;

and the Layout.module.css is:

/* Navbar */
.navbar {
  background-color: var(--primary-color);
  color: #fff;
  height: 70px;
}

.navbar ul {
  display: flex;
}

.navbar .flex {
  justify-content: space-between;
}

Structured like this, my .navbar .flex does not overwrite the global .flex class and split the h1 from the nav. How can I accomplish overwriting my global style from this component style?


Solution

  • Since .flex refers to a global class you'll need to use the :global selector to target it in your CSS module.

    /* Layout.module.css */
    
    .navbar :global(.flex) {
        justify-content: space-between;
    }
    

    Or using an alternate syntax.

    .navbar {
        :global {
            .flex {
                justify-content: space-between;
            }
        }
    }