使用 sass @each 或 @for 控制指令进行循环边距偏移

Vin*_*ent 2 html css sass

我是 sass 的新手,在练习时遇到了这种情况。

如何实现具有不同值偏移的上边距、右边距、下边距和左边距列表(我知道这可能听起来不清楚)。

所以这是 .scss 生成的 .css 文件的输出(应该是)

.offset-top-1{
    margin-top: 1rem;
}
.offset-top-2{
    margin-top: 2rem;
}
.offset-top-3{
    margin-top: 3rem;
}
//.... so on to .offset-top-6 and also for .offset-right-x, .offset-bottom-x, and .offset-left-x
Run Code Online (Sandbox Code Playgroud)

这是我的 .scss 文件

    @mixin offset-margin($margins){
        margin: $margins;
    }

    @for $i from 1 through 20 {
        .offset-top-#{$i}{
            @include offset-margin(1rem * $i 0rem 0rem 0rem); // the other offset values should be removed since I'm dealing only for margin-top
        }
        .offset-right-#{$i}{
            @include offset-margin( 0rem 1rem * $i 0rem 0rem);
        }
        .offset-bottom-#{$i}{
            @include offset-margin(0rem 0rem 1rem * $i 0rem);
        }
        .offset-left-#{$i}{
            @include offset-margin( 0rem 0rem 0rem 1rem * $i);
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑:

@mixin 指令offset-margin只允许“margin”,但我想要实现的是具有特定的边距位置,例如 margin-right、margin-left 等。

fca*_*ran 5

尝试这个代码(在http://sassmeister.com/上测试)

@mixin offset-margin($margin, $value){
  margin-#{$margin}: $value;
}

@for $i from 1 through 20 {
  @each $margin in top, left, bottom, right {

    .offset-#{$margin}-#{$i}{
      @include offset-margin($margin, 1rem * $i) 
    }

  }
}
Run Code Online (Sandbox Code Playgroud)