Kristin Yetter
Kristin Yetter

Reputation: 21

@for loop in a mixin in precss or sass

I have this great for loop in my precss style sheet. I would like to convert it to a mixin where i can pass the start values for $size (font-size) and $spacing(letter-spacing) for different media queries. I cannot get the variables to increment as i progress through the loop when i call it from a mixin. It works fine from the stylesheet

/*--adds .4 rem to each heading fz and character spacing 1-6---*/
$size: 1.8rem;
$spacing: 7px;
@for $i from 6 through 1 {
    h$i {
        font-size: resolve($size);
        letter-spacing: resolve($spacing);
        @extend %heading;
      }
        $size: $size + .4rem;
        $spacing: $spacing * 1.2;
    }

Upvotes: 2

Views: 2903

Answers (1)

BurpmanJunior
BurpmanJunior

Reputation: 1008

Your current code is close to working as a mixin when wrapped in a @mixin declaration in SCSS. The only tweak needed is outputting the $i in the selector using the #{$variable}

SCSS input:

%heading{
  /* heading properties */
  color: #999;
  font-family: sans-serif;
}

@mixin headingSize($size: 1.8rem, $spacing: 7px){
  @for $i from 6 through 1{
    h#{$i}{
      @extend %heading;
      font-size: $size;
      letter-spacing: $spacing;
    }
    $size: $size + .4rem;
    $spacing: $spacing * 1.2;
  }
}

@include headingSize($size: 2rem, $spacing: 10px);

This example uses your original $size and $spacing variables as default parameters in the mixin.

Here's an example JSFiddle in action.

CSS output:

h6, h5, h4, h3, h2, h1 {
  /* heading properties */
  color: #999;
  font-family: sans-serif;
}

h6 {
  font-size: 2rem;
  letter-spacing: 10px;
}

h5 {
  font-size: 2.4rem;
  letter-spacing: 12px;
}

h4 {
  font-size: 2.8rem;
  letter-spacing: 14.4px;
}

h3 {
  font-size: 3.2rem;
  letter-spacing: 17.28px;
}

h2 {
  font-size: 3.6rem;
  letter-spacing: 20.736px;
}

h1 {
  font-size: 4rem;
  letter-spacing: 24.8832px;
}

Upvotes: 4

Related Questions