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?

3 Answers 3

22

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

/** CSS MODULE FILE **/

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

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

Comments

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

2 Comments

Or you can just do import "../styles/Layout.module.css";
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.