How to override global CSS in a CSS module file?
Asked Answered
A

3

7

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?

Amary answered 16/2, 2021 at 0:36 Comment(0)
R
21

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;
        }
    }
}
Roadstead answered 19/2, 2021 at 0:46 Comment(0)
M
0

/** CSS MODULE FILE **/

.classname :global(.globalClass) { css properties }

.classname {
 :global {
  .globalClass { css properties }
 }
}
Merchandise answered 28/1, 2022 at 15:18 Comment(0)
S
-1

In NextJS and React when you import styles from "__.css" the styles becomes a variable so you have to use it in your HTML for it to take effect.

Currently you're not using any styles from your Layout.module.css, if you want to use that css you would change your html to: <div className={styles.navbar}> and such..

Selfcongratulation answered 16/2, 2021 at 1:39 Comment(2)
Or you can just do import "../styles/Layout.module.css";Atrophy
Sorry, I have edited my question to fix my typo. I am using the styles.navbar on the outer div. So I would think that the .navbar .flex selector would correctly select here and change justify-content to space between but that does not happen.Amary

© 2022 - 2024 — McMap. All rights reserved.