JAYDIP HIRAPARA
JAYDIP HIRAPARA

Reputation: 317

How to change value of global scss variable using mixin in scss?

I want to change value of variable $primary from the mixin based on theme. But It keeps the same value. How can I change it from based on theme ? In my style-variables.scss file

 $primary: #000;
    @mixin set-color-variable($theme) {
      $primary: #fff;
    }

But it keeps always value as #000 though i have different value in different theme.

Upvotes: 1

Views: 2917

Answers (1)

Arkellys
Arkellys

Reputation: 7811

The variable in your mixin is restricted to the scope of the mixin:

Variables declared at the top level of a stylesheet are global. This means that they can be accessed anywhere in their module after they’ve been declared. But that’s not true for all variables. Those declared in blocks (curly braces in SCSS or indented code in Sass) are usually local, and can only be accessed within the block they were declared.

So if you want to override $primary on the global level, you need to add a !global flag as:

@mixin set-color-variable($theme) {
  $primary: #fff !global;
}

However, since these variables are used only during compilation, it means that the new value will be used only for the code that is written after the mixin @include:

$primary: #000;

@mixin set-color-variable($theme) {
  $primary: #fff !global;
}

.color-1 { color: $primary; }
@include set-color-variable('');
.color-2 { color: $primary; }

Will compile as:

.color-1 { color: #000; }
.color-2 { color: #fff; }

Upvotes: 2

Related Questions