'How to check in SCSS if a variable exists and ha a value?

I am new in SCSS so bear with me :)

I have a use case where a SCSS variable --my-variable can exist and can have a value depending on some settings from the backend. So, if --my-variable exists and has a value I should override some styling. If not I shouldn't override anything.

Example:

In file1 I have:

.my-div {
    color: red;
    }

In file2 I should have something like this:

.my-div {
@include customize(color, --my-variable);
}

@mixin customize($property, $variable) {
  @if $variable and (var($variable)) {
    #{$property}: var($variable);
  }
}

The problem is that the if condition inside the mixin customize() is always true even if my document has no CSS variable called --my-variable. What am I doing wrong? Thank you



Solution 1:[1]

Sass has a function that check if the variable exists.

variable-exists()

$colorVariable: crimson;

@if variable-exists($colorVariable) {
   // Do some styling if the variable exists
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JayDev95