cssreactjsnext.js

Next js app styles not working on pages after refreshing the page


I am building my first next.js project, migrating from create-react-app and I am having this weird issue. If I am on home page and refresh the page, styles do persist, but if I go to "/profile" page for example, or any other page besides / page, and refresh the page, the CSS styles completely disappear.

Here is my folders structure:

folders/files

page.js: page.js

    
import BlogSection from '../components/BlogSection.jsx'
import Main from '../components/Main.jsx'
import ServiceSection from '../components/ServiceSection.jsx'
import '../styles/App.css'

export default function Home() {
    return (
        <div className='home-page-container'>
            <Main />
            <ServiceSection 
                homePage
            />
            <BlogSection />
        </div>
    )
}

layout.js: layout.js

import Footer from '@/components/Footer.jsx';
import Header from '../components/Header.jsx';

export const metadata = {
  title: "Movan",
  description: "Generated by create next app",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <Header />
        {children}
        <Footer />
      </body>
    </html>
  );
}

I do not even know what to try, because I am not familiar with Next at all.


Solution

  • The problem is that you've not added the globals.css file in your public layout.js file.

    To fix it just add this line in the starting of your code:

    import "./globals.css"
    

    OR since in your case the CSS file is ../styles/App.css add:

    import "../styles/App.css"
    

    This would be your layout.js afterwards:

    import "../styles/App.css" // ./globals.css
    
    import Footer from '@/components/Footer.jsx';
    import Header from '../components/Header.jsx';
    
    export const metadata = {
      title: "Movan",
      description: "Generated by create next app",
    };
    
    export default function RootLayout({ children }) {
      return (
        <html lang="en">
          <body>
            <Header />
            {children}
            <Footer />
          </body>
        </html>
      );
    }