How to implement `CSS` nested rules in `JSS`?
Asked Answered
A

3

25

I would like know how to work with css class-nesting in Material-UI or in JSS in general?
I am trying as below.

    card: {
      cardHeader:{
         marginTop:"30px"
      }
    }
Allegra answered 2/8, 2018 at 13:22 Comment(0)
C
30

For JSX like

<div className={classes.card}>
  <div className={classes.cardHeader}></div>
</div>

you can use:

card: {
  '& $cardHeader': {
      marginTop: 30,
  }
}

Targeting nested classes can be helpful if you override default JSS styles in Material UI components.

Cloaca answered 12/1, 2020 at 13:7 Comment(1)
how about a rule like '&-postfix'? The only way to reference this was using `${classes.card}-postfix`. Is this the correct way?Oman
P
18

It would be the same as writing CSS(not to be confused with SCSS or SASS). JSS transforms all js to pure CSS pretty much all CSS properties should work here as well.

card: {
 '& .cardHeader': {
   marginTop: 30 // px is default
 }
}

You will need to setup up plugins for this thanks @ricovitch for pointing out this. For default you can check thisjss-preset-default. For react you can simply use react-jss which has built-in default presets.

Prescriptible answered 28/8, 2018 at 13:55 Comment(3)
This does not work if you don't configure jss-nested pluginForetell
Have been using this with github.com/cssinjs/react-jss which does it out of boxPrescriptible
Appreciate your help! Worked for meMcvay
F
4

Material-UI includes a set of JSS plugins documented here : https://material-ui.com/customization/css-in-js/#plugins

In these plugins set there is jss-nested which allows for nested rules : http://cssinjs.org/jss-nested/

But in your sample code there is actually no need for nested rules, as you just need one : "cardHeader"

Foretell answered 3/8, 2018 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.