How to use Scoped Stylesheets (CSS) in Next.js

Posted by Ashutosh on April 10, 2021




In this article, we learn how to scope the stylesheets in Next.js. There are two kinds of CSS files:


  • Global CSS
  • Component CSS

Global CSS is accessible anywhere, whereas Component-based CSS is not available to the particular component only and is not accessible elsewhere. 


In Next.js, there is a styles folder for CSS. There is a file globals.css already present there. If you view the contents of _app.js, you can see the import of the globals.css file. 


import '../styles/globals.css'


Let's create the Next.js app using npx create-next-app


Create a new file 'hello.js' under the pages folder and update the following content:



function HelloPage() {
    return (
        <div>
            <div id="global" className="global">
                Hello there, I am global
            </div>
            <br />
            <div id="local">
                Hello there, I am scoped
            </div>
        </div>
    )
}


export default HelloPage;


In the globals.css add the following:


.global {
  color: red;
  font-size: larger;
}


Visit the URL, http://localhost:3000/hello. You will see "Hello there, I am global" in red color.


Create a new file, "Hello.module.css" under the styles folder. Add the following content:


.localclass {
  color: lightseagreen;
  font-size: larger;
}


Go to the hello.js, and add the following at the top of the file.


import styles from '../styles/Hello.module.css'


And also, modify the second div element (id=local) as ;


<div id="local" className={styles.localClass}>


Visit the URL http://localhost:3000/hello.




In this way, we use our stylesheets limited to the particular component or routes.