SCSS check for CSS custom var property

Viewed 1573

How do I conditionally apply a mixin if --my-custom-var is present? For example:

.test {
  @if var(--my-custom-var) {
     @include someExampleMixin()
  }

  @if var(--another-custom-var) {
     @include someExampleMixin()
  }
}

I don't care what the value of the --my-custom-var is but just want to check its existence.

1 Answers

Sass has introduced the variable-exists() function already in alpha. Be aware that Sass can only check for Sass variables. Therefor if you'd really want to use CSS variables you need to define the content of your CSS variable inside a Sass variable, for example $sassVar: /* content */; --cssVar: $sassVar;. Be also aware that the @if statement must be inside a @mixin or a @function to work. I posted a working example below, but here is aslo my Codepen Example since Stack doesn't compile Sass.

Note:

  • I used "null" inside my $var which basically expresses that there is no content within this variable, you can pass whatever you want it won't affect the outcome unless you remove or change the actual variable.
  • You can use multiple @if statements which I commented out in this example, but there should always follow an @else statement.

$var: null;

:root {
  --someVar: $var;
}

@mixin checkForVariable {
  @if variable-exists(var){
    body {
      background-color: red;
    }
  }
  //  @if variable-exists() {
  //    ...
  //  }
  //  @if variable-exists() {
  //    ...
  //  }
  @else {
    body {
      background-color: blue;
    }
  }
}

@include checkForVariable;

Related