Manish Sharma
Manish Sharma

Reputation: 3

Scss setting value of variable in selector causes it to change even if no element with given selector is available

SCSS File

$dark-theme: false!default;
$primary-dark: blue;

[dark-mode='dark'] {
  background:gray!important;
  $dark-theme: true!global;
}

[dark-mode='light'] {
  background:yellow!important;
  $dark-theme: false!global;
}

@if $dark-theme==true{
  $primary-dark: black!global;
} @else{
  $primary-dark: blue!global;
}

HTML

<html>
<body dark-mode="dark">
</body>
</html>

The above code always sets $dark-theme value given in [dark-mode='light'] while background is set correctly

Upvotes: 0

Views: 80

Answers (1)

Arkellys
Arkellys

Reputation: 7811

It seems that you misunderstood how SASS works. SASS variables are used only during compilation, hence once the code is compiled, they no longer exist.

The selectors [dark-mode='light'] and [dark-mode='dark'] are both always compiled regardless of whether there is an element with the value dark or light in your DOM. Since the light properties are the last set in the code, $dark-theme will always be false when it goes to your @if and so $primary-dark will always have the value blue.

If you want to keep this approach, you can take a look at CSS variables instead. Here is a nice article about this.

Upvotes: 1

Related Questions