0

I have helper classes like the following for all directions (both margin and padding):

.h-space-top-10 {margin-top: 10px;}
.h-space-top-20 {margin-top: 20px;}
.h-space-top-30 {margin-top: 30px;}

Is there anyway to create those with Sass to have dynamic values (e.g. up to 10x the base value 10px) or would one have to write them out manually?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • Possible duplicate of [SCSS/SASS: How to dynamically generate a list of classes with commas separating them](http://stackoverflow.com/questions/19087811/scss-sass-how-to-dynamically-generate-a-list-of-classes-with-commas-separating) – BenM Aug 31 '16 at 09:33
  • @BenM Please explain how you view the decleration blocks in your linked question dynamic? – Fellow Stranger Aug 31 '16 at 09:35

3 Answers3

1
@for $i from 1 through 3 {.h-space-top-#{$i * 10} {margin-top:#{$i * 10}px}}
Denis Sheremet
  • 2,453
  • 2
  • 18
  • 34
0
$properties: (margin padding);
$positions: (top right bottom left);
$range: 10;

@each $property in $properties  {
  @each $item in $positions  {
    @for $ii from 1 through $range {
        .h-#{$property}-#{$item}-#{$ii * 10} { #{$property}-#{$item}: #{$ii * 10}px; }
    }
  }
}
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
0

You may define two variables: number of repetitions and number of px to jump in each repetition. Something like this:

$numRepetitions: 3;
$pxJump: 10;

@for $i from 1 through $numRepetitions {
    .h-space-top-#{$i * $pxJump} {
            margin-top:#{$i * $pxJump}px
    }
}

The output for that case would be the code you need:

.h-space-top-10 {
  margin-top: 10px;
}

.h-space-top-20 {
  margin-top: 20px;
}

.h-space-top-30 {
  margin-top: 30px;
}

However, if you need for example to iterate 4 times and summing 5px in each jump you just need to change the value of the variables, like this:

$numRepetitions: 4; //4 instead of 3 repetitions
$pxJump: 5; //5px instead of 10px

@for $i from 1 through $numRepetitions {
    .h-space-top-#{$i * $pxJump} {
            margin-top:#{$i * $pxJump}px
    }
}

In that case you'll get this code:

.h-space-top-5 {
  margin-top: 5px;
}

.h-space-top-10 {
  margin-top: 10px;
}

.h-space-top-15 {
  margin-top: 15px;
}

.h-space-top-20 {
  margin-top: 20px;
}