Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Using sass @function inside @for

I have some sass function to create same margin, and it is inside loop like this

$short-margins: ( top: 'mt', left: 'ml', bottom: 'mb', right: 'mr' );
@for $i from 0 through 200 {
   @each $position, $prefix in $short-margins{
    .#{$prefix}-#{$i} {
      margin-#{$position}: #{$i}px;
    }
  }
}

This will create margin classes like this mr-0 and so on until mr-200, the problem is in line

margin-#{$position}: #{$i}px;

There I create px in loop, but i need that to be in rem? I ahve some function like this

$base-font-size: 14px;

// Remove units from the given value.
@function strip-unit($number) {
  @if type-of($number) == 'number' and not unitless($number) {
    @return $number / ($number * 0 + 1);
  }
  @return $number;
}

// convert only single px value to rem
@function single-px-to-rem($value) {
  $unitless-root-font-size: strip-unit($base-font-size);
  @return $value / $unitless-root-font-size * 1rem;
}

But when i want to use function inside loop like this

@for $i from 0 through 200 {
   @each $position, $prefix in $short-margins{
    .#{$prefix}-#{$i} {
      margin-#{$position}: single-px-to-rem(#{$i});
    }
  }
}

It does not compile throw me error, does any body knows how ti use sass @function inside @for?

Upvotes: 0

Views: 303

Answers (1)

Arkellys
Arkellys

Reputation: 7801

You are doing it right, but you need to send the $i value without interpolation:

@for $i from 0 through 200 {
   @each $position, $prefix in $short-margins{
    .#{$prefix}-#{$i} {
      margin-#{$position}: single-px-to-rem($i);
    }
  }
}

Upvotes: 1

Related Questions