Jason Dittmer
Jason Dittmer

Reputation: 37

SASS Functions with Variables

I'm fairly new to SASS functions and mixins. I would like to make a SASS function that multiplies a base spacing unit variable based on the number that is provided in the class name.

It would work like this. Say you had a variable called $base-spacing-unit with a value of 10. If you put the class ".pad-top-b5" on an HTML element it would give it a top padding of the $base-spacing-unit x 5.

The function might look something like this:

$base-spacing-unit: 10;

@function pad-top-b($val) {
    padding-top: ($base-spacing-unit * $val);
}

On the HTML element you could put a class like this:

<div class="pad-top-b10"></div>

And the element would have a top padding of 100px. Is this even possible with SASS?

Upvotes: 0

Views: 126

Answers (1)

3rdthemagical
3rdthemagical

Reputation: 5350

You can use a @for loop that generates a set of classes:

$class-slug: pad-top-b;
$base-spacing-unit: 10;
$classes-amount: 10;

@for $i from 1 through $classes-amount {
  .#{$class-slug}#{$i} {
    padding-top: ($base-spacing-unit * $i);
  }
}

Demo on SassMeister.

Upvotes: 3

Related Questions