SCSS repeat value?

2019-02-23 08:27发布

问题:

I'm trying to work out on SCSS how I would go about something like this:

I would like to have a margin anywhere between 1px and 1000px and have a class for it.

For example .MarginTop-x

X being where I can write any value. Obviously I couldn't write out

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

etc...

回答1:

Well you need a @for loop to do that .

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


回答2:

Not sure of the utility of this, 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;
}


标签: sass mixins