Home > OS >  CSS Modules not applying style - next.js 13
CSS Modules not applying style - next.js 13

Time:12-31

Using next.js 13.1.1 with /app

I've been doing all of my styles through a global.css up until now, but I'm trying to migrate them into CSS Modules.

In my root layout.js, I have a Header component that imports from ./header.js. This works fine with global.css.

I've made a module ../styles/header.module.css, and I import it into ./header.js with import styles from "../styles/header.module.css";, but then when I try to use it, for example with <h1 className={styles.big_title}>, none of the CSS is applied.

Any help would be much appreciated, I've been trying to fix this for hours. No errors occur, the CSS just doesn't apply.

// ./layout.js

import Header from "./header";
import Footer from "./footer";

import "../styles/global.css";

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
          <title>SB-Wiki</title>
      </head>
      <body>
          <Header />
          <main>
              {children}
          </main>
          <Footer />
      </body>
    </html>
  );
}
/* ../styles/header.module.css */

.big_title {
    color: red;
}
// ./header.js

import styles from "../styles/header.module.css";

export default function Header() {
    return (
        <header>
            <p className={styles.big_title}>Test</p>
        </header>
    )
}

The styles display if I add import styles from "../styles/header.module.css"; to the top of a page.js but that rather defeats the point of having a root layout.js as the framework is designed this way.

CodePudding user response:

You can use it like this styles["big_title"]

// ./header.js

import styles from "../styles/header.module.css";

export default function Header() {
    return (
        <header>
            <p className={styles["big_title"]}>Test</p>
        </header>
    )
}

CodePudding user response:

The problem is with next.js . You need to create config file for next.config.js in order to properly support your CSS .

module.exports = {
   cssModules: true,
     cssLoaderOptions: {
   importLoaders: 1,
  localIdentName: "[]",
 },
};

The config file will tell the next.js to treat your CSS files as CSS

CodePudding user response:

It could be the kebab-case. Try camelCase instead.

<p className={styles.bigTitle}>Test</p>
.bigTitle {
    color: red;
}

CodePudding user response:

Other answers may be work, also

Try this

To use CSS Modules with Next.js, add the following to your next.config.js file to enable the CSS loader:

const withCSS = require('@zeit/next-css');
module.exports = withCSS({
  cssModules: true,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: '[local]___[hash:base64:5]',
  },
});

  • Related