简体   繁体   中英

React css class names are global?

I'm not going to delve into the code too much in this question, instead, I'm looking for a high-level answer.

In my js, I have a div with the class name potato . I have a file called myStyles.css , and I imported that CSS file into my js file. Now in my CSS, I targeted .potato , and do my styling. All good so far.

Now I create a new js file, and in that new file I again have a div name by potato . In this new js file, I do not import myStyles.css . However, for some reason, the styling from myStyles.css is being applied to that div!

Please let me know why this is the case? Why is it pulling styling from an unimported file?

If you need any actual code on my part to answer this question, please let me know and I can provide it.

Thanks!

I got the same problem which you are facing. So if you make a simple css file with class then it will work as a global file. so the solutions are following:

1-> Import css as module and use it

2-> Don't use same class or don't give css directly to element

The css will be global for all components.
Even if you import individual css for all components, it will still apply it to all other components.

To fix this, just add and "id" or "class" to the parent and then use that parent element's id to access its classes.

#myComponent .first{
   /* your css */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM