How to use child selectors in JSS
Asked Answered
T

2

23

I'm experimenting with JSS to see if it is realistic to migrate a Sass code base. I have a very basic example of a CSS style that, when hovered, modifies the style of a child node.

span {
  color: red;
}

button:hover span {
  color: blue;
}
<button>
  <span>Click Me</span>
</button>

I am unsure how to write this in JSS. Something I have tried looks like:

const styles = {
  button: {
    '&:hover': {
      span: {
        color: 'blue',
      }
    }
  },
  span: {
    color: 'red',
  }
}

const { classes } = jss.createStyleSheet(styles).attach()

document.body.innerHTML = `
  <button class=${classes.button}>
    <span class=${classes.span}>Click Here</span>
  </button>
`

Thanks!

Titanomachy answered 29/6, 2018 at 5:12 Comment(0)
H
18

Have you tried doing:

const styles = {
  button: {
    '&:hover span': {
       color: 'blue',
    }
  },
  span: {
    color: 'red',
  }
}
Harshman answered 29/6, 2018 at 5:45 Comment(4)
Thanks! How would it work if it was a class name that did not match an element selector. For instance if it was someClass.Titanomachy
@JonSakas, prefix the class with a $. For example: "&:hover $someClass"Catboat
when hovered on the button, is this code gonna change all span element's color or the span elements which are nested in the button?Homogeneity
hi @deowk, is there any way to access the parent element using the child element in JSSShawn
B
13

As mentioned in the comment by @cwouter, if it was a class name, you can do something like this.

const styles = {
  button: {
    '&:hover $some_class_name': {
       color: 'blue',
    }
  },
  some_class_name: {
    color: 'red',
  }
}
Bulgar answered 27/5, 2020 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.