Home > Software design >  How to style child elements with vanilla extract?
How to style child elements with vanilla extract?

Time:01-03

I am starting to use vanilla extract to style a NextJS app. Is there any way to style child elements from the parent without creating another class?

I have an structure like this in the react component:

 <ul className={styles.ul}>
   <li>a</li>
   <li>b</li>
   <li>c</li>
 </ul>

And something like this in the style file:

import { style } from "@vanilla-extract/css"

export const ul = style({
    display: vars.display.flex,
    listStyleType: vars.none,
})

CodePudding user response:

You can use & notation with help of css selector like nth-child in your style as i show below:

Edit: This snippet code wont work at all :(

  export const ul = style({
    display: vars.display.flex,
    listStyleType: vars.none,
    selectors:{
      '& li:nth-child(n)': {
          display: vars.display.flex,
      }
    }
  })

In fact, & represent your style like you may know in css. .class-name:nth-child. & means class-name in this example.

Edit: As vanilla extract documentation noted: To improve maintainability, each style block can only target a single element. To enforce this, all selectors must target the “&” character which is a reference to the current element.

For example, '&:hover:not(:active)' and [${parentClass} &] are considered valid, while '& a[href]' and [& ${childClass}] are not.

If you want to target another scoped class then it should be defined within the style block of that class instead.

For example, [& ${childClass}] is invalid since it doesn’t target “&”, so it should instead be defined in the style block for childClass.

If you want to globally target child nodes within the current element (e.g. '& a[href]'), you should use globalStyle instead.

useful links:
https://github.com/seek-oss/vanilla-extract
https://tsh.io/blog/vanilla-extract-library/

  • Related