Ricky
Ricky

Reputation: 3072

Unable to use CSS Custom Properties (aka CSS Variables) with SASS @if Statement

I'm trying to pass some CSS Custom Properties to a SASS Mixin. I'm able use the variables when applied directly in the styling I want. But when I try to use a variable in an If statement, it doesn't work.

Mixin Example:

@mixin bg-color($hue, $status) {
  background: hsl($hue, 50%, 50%); // $hue works as expected

  @if $status == 'danger' { // doesn't work!
    color: 'red';
  } @else if $status == 'warning' { // doesn't work!
    color: 'orange';
  } @else { // always enters the else branch
    color: 'black';
  }
}

CSS:

:root {
    --hue: 195;
    --status: 'default';
}

.demo {
    @include bg-color(var(---hue), var(---status));
}

If I manually add the status value to the mixin, it works:

.demo {
    @include bg-color(var(---hue), 'danger');
}

Any idea what might be the issue?

UPDATE: As @temani-afif mentioned, this approach isn't possible because SASS files are compiled before CSS variables are used.

Upvotes: 1

Views: 1422

Answers (1)

Dima Malko
Dima Malko

Reputation: 283

If you have some file, where you import all SCSS files, it depends which is imported first and which are imported after.

Make sure that one that you need to be Read by VS is first.

For example i needed to read first my variables, so it have to be first, other way, my code read mixin, and doesnt know yet what is '$blue'.

Upvotes: 1

Related Questions