SCSS repeat value?

I am trying to figure out SCSS, as I would do something like this:

I would like to have margins somewhere between 1px and 1000px and have a class for it.

For example .MarginTop's

X where I can write any value. Obviously, I could not write

.MarginTop-1 {margin-top:1px}
.MarginTop-2 {margin-top:2px}
.MarginTop-3 {margin-top:3px}
.MarginTop-4 {margin-top:4px}

etc.

+4
source share
2 answers

For this you need a loop @for.

SCSS:

$class-slug: ".MarginTop";
$stop-loop:  4;

@for $i from 0 through $stop-loop {
  #{$class-slug}-#{$i} {
    margin-top: #{$i}px;
  }
}

Compiled CSS:

.MarginTop-0 {
  margin-top: 0px; }

.MarginTop-1 {
  margin-top: 1px; }

.MarginTop-2 {
  margin-top: 2px; }

.MarginTop-3 {
  margin-top: 3px; }

.MarginTop-4 {
  margin-top: 4px; }
+3
source

Not sure if this is useful, but ...

Sass

@mixin marginTop($amount) {
  .marginTop-#{$amount} {
    margin-top: unquote($amount + 'px');
  }
}

@include marginTop(1);
@include marginTop(100);

Compiled CSS :

.marginTop-1 {
  margin-top: 1px;
}

.marginTop-100 {
  margin-top: 100px;
}
0
source

Source: https://habr.com/ru/post/1535458/


All Articles