如何覆盖 CSS 模块文件中的全局 CSS?

How to override global CSS in a CSS module file?

让我在 Next.js 项目的 global.css 文件中说:

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

我还有一个 Layout.js 组件和一个 Layout.module.css 文件。该组件如下所示:

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;

Layout.module.css 是:

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

.navbar ul {
  display: flex;
}

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

这样的结构,我的 .navbar .flex 不会覆盖全局 .flex class 并将 h1nav 中拆分出来。如何从该组件样式覆盖我的全局样式?

在 NextJS 和 React 中,当你 import styles from "__.css" styles 成为一个变量,因此您必须在 HTML 中使用它才能生效。

目前您没有使用 Layout.module.css 中的任何样式,如果您想使用 css 您可以将 html 更改为:<div className={styles.navbar}> 等等..

由于 .flex 指的是全局 class,您需要使用 :global 选择器在 CSS 模块中定位它。

/* Layout.module.css */

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

/** CSS 模块文件 **/

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

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