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?

2

3 Answers 3

1
@for $i from 1 through 3 {.h-space-top-#{$i * 10} {margin-top:#{$i * 10}px}}
Sign up to request clarification or add additional context in comments.

Comments

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; }
    }
  }
}

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.