Can I use Sass properties as args for my function?

Viewed 33

It appears that I'm attempting to use SASS properties as arguments for my function, AND IT'S NOT GOING WELL.

Is there a way in which I can do this, or is there a better alternative to what I'm trying to achieve?

Basically, I want to change the values of variables I send to my function based on my screen width media query.

Currently:

@function myFunc($arg1, $arg2) {
    @debug "arg1 = #{$arg1} / arg2 = #{$arg2}";

    @return #{$arg1} * #{$arg2};
}

.my-class {
    // Mobile first values
    --var1: 10px;
    --var2: 20px;

    @media (--from-tablet-size) {
        --var1: 20px;
        --var2: 40px;
    }

    width: myFunc(--var1, ---var2);
}

The debug output actually shows that the values passed to the function is just the strings --var1 and --var2 rather than their respective property values...

DEBUG: arg1 = --var1 / arg2 = --var2

Is there something that I can do to solve this? Either by passing the properties as I am attempting here, or a better alternative?

1 Answers

There are some problems with your code:

  1. For reading CSS variables var() is needed, for example var(--var1). More information: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
  2. CSS variables can't use with SASS calculations or functions.
  3. Two numbers with units can't multiply in SASS for example. What expected from 10px * 20px? It should be something like 10 * 20px.

First suggestion: Using SASS variables

@function myFunc($arg1, $arg2) {
    @debug "arg1 = #{$arg1} / arg2 = #{$arg2}";

    @return $arg1 * $arg2;
}

.my-class {
    // Mobile first values
    $var1: 10;
    $var2: 20px;
    width: myFunc($var1, -$var2);

    @media (--from-tablet-size) {
        $var1: 20;
        $var2: 40px;
        width: myFunc($var1, -$var2);    
    }
}

Second suggestion: Using CSS variables

.my-class {
    // Mobile first values
    --var1: 10;
    --var2: 20px;

    @media (--from-tablet-size) {
        --var1: 20;
        --var2: 40px;
    }

    width: calc(var(--var1) * -1 * var(--var2));
}
Related