2

I am trying to change value of CSS variable based on another variable. I want to check if current value of variable is white then set it to black... In some class suppose my variable is --default-var, value of --default-var can be any color.... If value of default-var is white then change it to black i tried

.my-class{
   @if var(--default-var) == #fff{
            --default-var : #000;
        }
}

I have also tried

.my-class{
   @if --default-var == #fff{
            --default-var : #000;
        }
}

both cases are not working..please help.

Vish
  • 139
  • 2
  • 11
  • 1
    It looks like you are trying to implement themed elements. Could you make two different classes `.my-class-white` and `.my-class-black`. Then you can toggle between these classes by javascript. – Shubham Yerawar Mar 26 '21 at 10:42
  • @ShubhamYerawar i have to use --default-var in many other classes as well after changing it value....using 2 classes won't help in my case. – Vish Mar 26 '21 at 11:09

2 Answers2

0

Best practice here is to create two classes with the different CSS values and then toggle the class using logic such as in C# Razor or Javascript. This keeps it cleaner to read.

Nathelol
  • 577
  • 7
  • 25
  • 1
    i have to use --default-var in many other classes as well after changing it value....using 2 classes won't help in my case @Nathelol – Vish Mar 26 '21 at 11:09
0

You can not use this kind of Logic in CSS. There are workarounds though.

Use a Preprocessor

You could use either SASS or Less to create CSS-Files that are created conditionally based on variables that you can set yourself. This however only helps if you´re decision is made on build-time. So this will not help you if you want to react to user input.

This is not entirely true, as there are some pseudo selectors that in the end can change styles based on user input. However, you can not use them to react to variables set in your CSS.

Use Javascript

With Javascript you can manipulate elements and their style-Property or their class-List directly. In order to control under what condition you want these changes to be made you can use all the tools that you have in Javascript.

You could read what value your css variable has and then change styles on other classes based on that value.

Just Google for js DOM manipulation or setting css with js. In order to provide better ressources i´d need some more information on what exactly you want to do. This may be what you are looking for: https://stackoverflow.com/a/51860936/11930769.

j-toscani
  • 96
  • 4