CSS splitting per page in Next.js

Viewed 5183

I need my css stylesheet split into many files, one per each Next.js page. How to implement this?

I tried to use next-css and just import a css-file into each page. It almost works. However the css-file is not loaded on Link navigation. Authors of Next say it's not implemented: https://github.com/zeit/next-plugins/issues/282#issuecomment-523128645

I also tried using styled-jsx. It has several problems for me. It has many bugs on its Issues page. I also failed to make styles visible throughout child components with this approach.

2 Answers

You can import a module.css (import style from 'root/styles/MyStyle.module.css) and use as follows.

This is your component:

import style from '../../styles/components/Header.module.css'

export default function Header() {
    return (
        <h1 className={style.header}>
            Hello World
        </h1>
    );
}

This is your CSS:

.header{
    color: #fff;
    width: 100%;
    height: 80px;
}

Note that the CSS class is used as the components className;

Or, inside the react component, you can try adding the tag <style jsx>{ your_CSS_here }</style>.

According to Next documentation each page uses the styled-jsx library. But you can still use other CSS-in-JS libraries such as Styled Components and Emotion.

Next apps has also support for using sass that allow you to import .css and .scss files.

For more information you can check the Vercel Docs. I also recommend you to check the Learning area.

You can create your seperate css files and on each component that you need specific styling you import the css file that is unique to that component. so for example say you have a Component in file file1.js then you can import styles specific to this component in the file file1.css same happens for another file file2 with css file2.css

import './file1.css'; //importing the style specific only for this component
function File1(){
      const [processing, setProcessing] = useState(false)

    return (
        <> </>
    )
}
export default File1

Similarly for the second file

import './file2.css'; //css file specific to this component 
function File2(){
      const [processing, setProcessing] = useState(false)

    return (
        <> </>
    )
}
export default File2
Related