Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS splitting per page in Next.js

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.

like image 499
Gherman Avatar asked May 30 '26 13:05

Gherman


1 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.

like image 79
João Augusto Tonial Laner Avatar answered Jun 02 '26 01:06

João Augusto Tonial Laner