šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Fixing the – selector “body” is not pure (pure selectors must contain at least one local class or id) – error in NextJs

While working on some CSS styling experiments for a NextJs page I got the below error:

Selector "body" is not pure (pure selectors must contain at least one local class or id)

Why the error happened?

Because ... CSS modules. In a CSS module, you can't directly have simple element selectors such as:

body {/* rules here */}
/* or */
div {/* rules here */}

I was having the following structure in my app folder:

/app
    layout.js
    page.js
    utils.module.css    

Somewhere in the utils.module.css file, I was trying to change the background color of the body element:

/*app/utils.module.css*/
body { /*... */}
.my-form { /*... */}

And given that in a CSS module, you can only have selectors that are based on a class or id, the error was thrown.

Who to fix it?

There are two ways we can fix this error.

Option 1: put all the general styling in a global css file.

This should be the optimal solution in most cases.

Anything that has to do with the general styling should go in a global CSS file, not into a module. Something like this:

/*app/global.css*/
* { ... }
body { ... }
p {...}

And we can import it in the general layout file:

// app/layout.js
import "./global.css";
export default function StyledRootLayout({ children }) {
  return (
    <html>
      <head />
      <body>{children}</body>
    </html>
  )
}

This will ensure that the rules from global.css are applied to all the pages.

The utils.module.css module file should be imported only where the classes and ID's contained in it are needed.

Option 2: add a class to the body element

Another way to fix it is to add a class (or id) to the targeted element:

/*app/utils.module.css*/
body.test {
    border: 2px solid blue;
}

And we can later import the module and use the class:

// app/layout.js
import "./utils.module.css";
export default function StyledRootLayout({ children }) {
  return (
    <html>
      <head />
      <body className={`${styles.test}`}>{children}</body>
    </html>
  )
}

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *