2

I would like to make a CSS module index.module.css as follows which will be only used by App component :

.my-class {
  color: red;
}

label {
  color: blue;
}

In App.js I use import style from "./index.module.css"; to import it, whereas Bpp.js does not import ./index.module.css.

Then, I realize that my-class in Bpp does not apply color: red;, which is expected. However, label in Bpp does apply color: blue; which is not what I wanted.

Here is the code: https://codesandbox.io/s/small-pine-6cpxcx?file=/src/App.js

Note that the css became ._src_index_module__my-class { color: red; } label { color: blue; }, where label did not change: enter image description here

Does anyone know if it is possible to privatize label {color: blue} only for the App component so as to prevent it from being applied to other components?

isherwood
  • 58,414
  • 16
  • 114
  • 157
SoftTimur
  • 5,630
  • 38
  • 140
  • 292
  • Does this answer your question? [How to make React CSS import component-scoped?](https://stackoverflow.com/questions/47090574/how-to-make-react-css-import-component-scoped) – isherwood Dec 29 '22 at 16:16
  • @isherwood Thank you for the reference. I would like to have a certain answer about element type selectors such as `label`, `button`, `input`. – SoftTimur Dec 29 '22 at 16:34
  • You will need a class-based approach to use the style on a specific component. – DreamBold Dec 29 '22 at 16:36
  • `label.my-label { color: blue; }` Or something like that – DreamBold Dec 29 '22 at 16:37
  • See my answer's section about _app scoped normalize_ https://stackoverflow.com/questions/72693841/effectively-using-sass-scss/72697281#72697281 – Martin May 31 '23 at 10:51
  • I find it really puzzling why people are trying so hard to make CSS files behave like inline styling, when that is the very problem they are meant to be solving... If you really want to apply styles very specifically and don't want a selector that selects 'all tags of type X' to apply to tags of type X, why not just apply them inline..? – Joey Sabey Jun 15 '23 at 16:01

2 Answers2

2

CSS module's can't privatize styles created on element types, you will need to assign your element a class, or select the element type as a descendant of some class that can be privatized.

borderr
  • 165
  • 4
1

Add these elements into another div with an id selector. Then give style with catching with div as giving styles to children.

after that, Give all property values as !important inside the app component which you are going to styles

#{div id selector name} > {element name} {
  property: value !important;
}

The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.

if you need more details of child combinator in CSS refer this link Child combinator