Search code examples
csscss-variables

Can I assign a CSS variable to another?


Can I assign one globally defined CSS variable to another locally define variable?

For example, the variable --dark has been globally defined as black.

Then, I want to be able to do:

:root {
    --background-color: --dark
}

.light {
    --background-color: white
}

div {
   background-color: --background-color
}

So that by default, my div will have a black background. And when the class light is added to it, it will have a white background.

I need the 'default' --dark variable here because it is a theme variable.


Solution

  • You should assign as var(--dark)

    :root {
        --dark : black;
        --background-color: var(--dark);
    }
    
    .light {
        --background-color: white;
    }
    
    div {
      height: 100px;
      width: 100px;
      background-color: var(--background-color);
    }
    <div class="light"></div>
    <div></div>