Search code examples
cssreplacenestedcss-variables

is there a way to assign a different cssVariable to a cssVariable based on the class it is nested in?


we are using a design system that has 'tokens' and 'primitives'.

the idea is that we can connect different baseColors to a different UI-elements depending on the brand.

    <h1>Hi this is header</h1>
    
    <div class="branded">
      <h1>Hi this is header</h1>
    </div>
:root{
  --primary:          red;
  --headercolor: var(--primary);
}

.branded{
  --primary: blue;
}

h1{
  color: var(--headercolor);
}

I tried creating a demo project and adding and replacing variables.

I expected the nested variable to change the token variable, but this is not the case, and it uses the one set in :root

edit we cant do the following as we can only set 1 class on the body, and there are too many elements to handpick like this.

:root {
  --primary: red;
}

h1 {
  color: var(--primary);
}

.branded h1{
  --primary: blue;
}

Solution

  • You almost got it right. To make it work you just need to redefine the variables within the .branded class and their dependant variables. All elements within that class will automatically inherit the correct colors based on the scoped variables.

    <html>
    <head>
      <style>
        :root {
          --primary: red;
          --headercolor: var(--primary);
        }
        .branded {
          --primary: blue;
          --headercolor: var(--primary);
        }
        h1 {
          color: var(--headercolor);
        }
      </style>
    </head>
    <body>
      <h1>header</h1>    
      <div class="branded">
        <h1>branded header</h1>
      </div>
    </body>
    </html>