Create a Sass loop within a mixin

How would one go about creating a reusable mixin containing this loop?

here’s the loop:

  @for $i from $from to $to{
    .text-#{$i}{
    font-size: 10px * $i;
   }
}

and here’s how I tried including a mixin, but doesn’t seem to be working:

@mixin fontSize($from: 1, $to: 6){
  @for $i from $from to $to{
    .text-#{$i}{
    font-size: 10px * $i;
   }
  }
}  

p{
@include fontSize(1, 5);
}
  
</style>

<p class="text-1">Hello</p>
<p class="text-2">Hello</p>
<p class="text-3">Hello</p>
<p class="text-4">Hello</p>
<p class="text-5">Hello</p>

Appreciate any feedback on this!

try changing this to:

p {
    @include fontSize($from: 1, $to: 5);
}

Edit: one other problem is that you are calling the mixin from within the p selector
so you can’t have .text-* inside of the p (that doesn’t work in regular css so it won’t work here)

Try making a parent tag like and put the include statement in the main tag instead…

1 Like

here’s a pen showing the code with all the fixes mentioned applied (plus a few more)

1 Like

thanks so much for the help! I got it to work. Just a question- why does the include get called in this manner:

@include fontSize($from: 1, $to: 5); 

instead of

@include fontSize(1, 5)

I would not have known to include the $from and $to in the arguments when calling the mixin. Thanks again for your help :slight_smile:

I think it works even if you just pass the parameters as is without the names. I thought the names were needed but from my testing, it works without also.

1 Like