Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting Pure elements in next.js with CSS modules

I'm porting an app from React to Next and I keep getting an error with my css: "ul" is not pure (pure selectors must contain at least one local class or id).

I'm using css modules and am not sure what the workaround is to keep everything in the css module.

for example:

index.js

<div className={styles.container}>
  <ul>
    <li>Person One</li>
  </ul>
</div>

index.module.css

.container{
  background-color: pink;
}
ul{
  list-style-type: none; //this throws an error
}
like image 808
lernbr Avatar asked Jun 19 '20 10:06

lernbr


2 Answers

If you don't want to use classes as mentioned @Zeeshan's answer, you cannot use the module-based CSS. You will need to use a global stylesheet to target pure elements as selectors. They cannot be component-scoped.

Further, you can only import a global stylesheet in one place (_app.tsx/_app.jsx/_app.js), or you'll receive an error (explained here).

You may break your styles out across many stylesheets, but they all have to be global, so there's probably little benefit from doing so.

To quote directly from this Next.js GitHub discussion forum:

You are receiving this error because you are using html tags directly instead of classnames or ids in a file extension that is probably [filename].module.(css | scss | sass)

File extensions with *.module.(css | scss | sass) are css modules and they can only target elements using classnames or ids and not using tag names. Although this is possible in other frameworks like create-react-app, it is not possible in next-js.

My suggestion is using these html selector css in a separate file that doesn't contain the '.module' in it. Example: [filename].(css | scss | sass) --> styles.scss

And instead of importing like this

import styles from './styles.module.scss';

import like this

import './styles.scss';

like image 89
tarrball Avatar answered Sep 19 '22 08:09

tarrball


The question might be a little old, but I want to describe another way to do what you desire in a simple way that I find easy to understand.

You can add a container class to the top element (just like you did), and then use combinators ( ,+,> and etc..) to target pure elements as you wish.

For example:

index.js

<div className={styles.container}>
    <ul>
        <li>Person One</li>
    </ul>
</div>

index.module.css

.container {
  background-color: pink;
}
.container ul {
  list-style-type: none;
}
like image 30
Oz Heymann Avatar answered Sep 19 '22 08:09

Oz Heymann