Search code examples
csssass

css variables in darken, lighten function


I need to change the colors dynamically from the button. First I am declare the css variable and then declare the scss varaibe to the css variable. It's perfectlly working. But when I try to put the darken or lighten scss function, it throws the error as it's not color.

I need to know, how to do.

In variable.scss

:root{
  --primary_color:rgba(0, 0, 0, 1);
  --secondary_color:#ffffff;
}

/* Only use  #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color(). Mui not support other farmates */
$primary_color:  var(--primary_color);
$secondary_color: var(--secondary_color);

when I am tring to create new vaiable as $list_button_hover:hover_color($hover);

@function hover_color($color){
    @if(lightness($color) < 50%){
        @return lighten($color,30%);
    }@else{
        @return darken($color,10%);
    }
}

It throws error as

ERROR in ./src/Components/Sidnavbar/Sidnavbar.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/Components/Sidnavbar/Sidnavbar.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
  ╷
4 │ $list_button_hover:hover_color($hover);
  │                                ^^^^^^
  ╵
  src/Components/Sidnavbar/Sidnavbar.scss 4:32  root stylesheet

webpack compiled with 1 error and 1 warning

I need to change the color dynamically with

    const root = document.documentElement;
root.style.setProperty("--primary_color", "#fff");

Solution

  • Based on this info, my presumption is that you want to compute a hover color dynamically based on the value of a CSS variable that can change at runtime.

    Note that you can't rely on Sass functions at runtime. They are run at the time of transpilation to CSS, not while your website is "running".

    If you're hoping to change --primary-color using JavaScript dynamically at runtime, you can't use Sass functions to generate ancillary colors.