csssass

Calculating using sass variables for properties with multiple values


I have two sass variables I'm using to set different sets of margin values as follows:

$variable-big: 2.5rem 1rem 1.8rem 1.2rem;

$variable-small: 1.1rem 0.7rem 0.7rem 0.1rem;

I'm a total novice sass user from a design background so please bear with me if I get the terminology wrong in describing my problem and I'm just being stupid in something that is probably obvious to other users.

I want to be able to have a new variable to calculate the difference between the two sets of values.

So something like this...

$variable-difference: $variable-big - $variable-small

So that I can use it like this

.spacer-top {
margin: $variable-difference;
}

To output this:

.spacer-top {
margin: 1.4rem 0.3rem 1.1rem 0.1rem;
}

I've been trying to read up on how to do this and have tried various things to little success:

$variable-difference: $variable-big - $variable-small

returns: margin: 2.5rem 1rem 1.8rem 1.2rem-1.1rem 0.7rem 0.7rem 0.1rem;

$variable-difference: ($variable-big) - ($variable-small) 

returns the same: margin: 2.5rem 1rem 1.8rem 1.2rem-1.1rem 0.7rem 0.7rem 0.1rem;

$variable-difference: ($variable-big - $variable-small) 

the same: margin: 2.5rem 1rem 1.8rem 1.2rem-1.1rem 0.7rem 0.7rem 0.1rem;

 $variable-difference: (#{$variable-big} - #{$variable-small}) 

the same: margin: 2.5rem 1rem 1.8rem 1.2rem-1.1rem 0.7rem 0.7rem 0.1rem;

Self-evidently, I don't know what I'm doing. Any help appreciated!


Solution

  • Since those variables are actually lists, you may use the nth(<list>, <index>) function to retrieve the nth element of a list (Doc)

    $variable-big: 2.5rem 1rem 1.8rem 1.2rem;
    $variable-small: 1.1rem 0.7rem 0.7rem 0.1rem;
    
    
    div {
       margin: 
       nth($variable-big, 1) - nth($variable-small, 1)
       nth($variable-big, 2) - nth($variable-small, 2)
       nth($variable-big, 3) - nth($variable-small, 3)
       nth($variable-big, 4) - nth($variable-small, 4);
    }
    
    
    /* Output
    
    div {
        margin: 1.4rem 0.3rem 1.1rem 1.1rem;
    }
    */
    

    SassMeister demo

    Further reference on lists in this article by Kitty Giraudel