Search code examples
javascriptcssreactjsstyled-componentscss-variables

Css variable interpolation Styled Components


I have a component for example:

const pretty = styled.div`
  --nth-child: 5n;
  --size: 20px; //css variable
  
  width: var(--size);

  &:nth-child(var(--nth-child)) {
    //...styles...
  }

  @media (max-width: 768px) {
    //overriding
    --size: 12px;
    --nth-child: 3n;
  }
`

The question is how to interpolate css variable in this place?

&:nth-child(var(--nth-child)) {
  //...styles...
}

If I understood correctly this is impossible so it would be nice to find another solution

Note: I can't use JS variables in my case

Update:

Also editor highlights the error there:

enter image description here

so I tried this, but this does not work either:

&:nth-child(${css`var(--nth-child)`}) {
  margin-right: 0;
}

Solution

  • So you can't use CSS variables for anything but property declarations. They don't work in selectors.

    But I think you should be able to achieve the same here by other means. I know you mentioned I can't use JS variables in my case and probably your usecase is less straightforward than the example, but can't you either just use React props interpolation that comes with styled-components

    &:nth-child(${p => p.nthChildLargeScreen}) {
      //...styles...
    }
    
    @media (max-width: 768px) {
      &:nth-child(${p => p.nthChildLargeScreen}) {
        //...reverse styles from above...
      }
    
      &:nth-child(${p => p.nthChildSmallScreen}) {
        //...styles...
      }
    }
    

    Or even just global variables?

    &:nth-child(${NTH_CHILD_LARGE_SCREEN}) {
      //...styles...
    }
    
    ...etc
    

    If you can write the styled component, and define CSS variables, in the first place, seems like you should be able to do at least one of the above instead.