search

Home  >  Q&A  >  body text

Why do my CSS styles disappear after refreshing the page in Next.js?

I created a CSS folder in the application folder and wrote the CSS files in it. Then import them into components for use. They are applied on first load. But when I refresh the page, they are all gone. My folder structure

I tried going back and saving the files again and it worked but disappeared every time I refreshed again.

P粉461599845P粉461599845376 days ago526

reply all(1)I'll reply

  • P粉517475670

    P粉5174756702024-01-01 00:39:15

    In the following js, CSS cannot be loaded in each single page component. Can only be loaded inside pages/_app.js

    import '../styles.css'
    
    // This default export is required in a new `pages/_app.js` file.
    export default function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />
    }

    If they need to be called inside a single component, they should be CSS modules.

    For example: components/layout.js

    import styles from './layout.module.css';
    
    export default function Layout({ children }) {
      return <div className={styles.container}>{children}</div>;
    }

    In components/layout.module.css

    .container {
      max-width: 36rem;
      padding: 0 1rem;
      margin: 3rem auto 6rem;
    }

    More content can be found here

    reply
    0
  • Cancelreply