1

我有以下 SCSS mixin,它从.grid1to生成 CSS 类.grid12

$columns: 12;
@mixin repeat($character, $n) {
    $c: "";
    @for $i from 1 through $n {
        $c: $c + $character;
    }
    -ms-grid-columns: unquote($c);
}


// classes for defining number of equally sized (sub-)grid columns
@mixin grid-x {
    @for $i from 1 through $columns {
        .grid#{$i} {
            @include repeat(" 1fr", $i);
        }
    }
}

@include grid-x;

使用 libsass 生成的 CSS 类如下所示:

.grid1 {
  -ms-grid-columns:  1fr;
}

.grid2 {
  -ms-grid-columns:  1fr 1fr;
}

.grid3 {
  -ms-grid-columns:  1fr 1fr 1fr;
}
...

由于 IE 11 不支持grid-gap我想在生成的列之间插入 20px 间隙列。

预期结果如下所示:

// nothing changed for .grid1
.grid1 {
  -ms-grid-columns:  1fr;
}

.grid2 {
  -ms-grid-columns:  1fr 20px 1fr;
}

.grid3 {
  -ms-grid-columns:  1fr 20px 1fr 20px 1fr;
}
...

简单地20px在重复字符串中添加列会导致不需要的尾随20px

@include repeat(" 1fr 20px", $i);

结果是

.grid1 {
  -ms-grid-columns:  1fr 20px;
}                        ^^^^

.grid2 {
  -ms-grid-columns:  1fr 20px 1fr 20px;
}^                                ^^^^

.grid3 {
  -ms-grid-columns:  1fr 20px 1fr 20px 1fr 20px;
}                                          ^^^^
...

任何想法如何使用 SCSS mixins 获得所需的结果?

为了方便测试,只需将 mixins 粘贴到sassmeister上即可。

4

2 回答 2

1

您可以为间隙包含另一个变量并这样做。

$columns: 12;
@mixin repeat($character, $gap, $n) {
    $c: "";
    @if ($n != 1) {
      @for $i from 1 through ($n - 1) {
          $c: $c+" "+$character+" "+$gap ;
      }
    }
    $c: $c+" "+$character ;
    -ms-grid-columns: unquote($c);
}


// classes for defining number of equally sized (sub-)grid columns
@mixin grid-x {
    @for $i from 1 through $columns  {
        .grid#{$i} {
            @include repeat("1fr","20px", $i);
        }
    }
}

@include grid-x;

如果您在间隙中指定和空字符串,这也将为您提供初始结果:

于 2018-09-04T10:48:43.267 回答
1

我能够自己使用以下方法解决它@if () { } @else { }

$columns: 12;
@mixin repeat($character, $n) {
    $c: "";
    @for $i from 1 through $n {
      @if ($n == 1 or $i == $n) {
        $c: $c + $character;
      } @else {
        $c: $c + $character + " 20px";
      }  
    }
    -ms-grid-columns: unquote($c);
}


// classes for defining number of equally sized (sub-)grid columns
@mixin grid-x {
    @for $i from 1 through $columns {
        .grid#{$i} {
            @include repeat(" 1fr", $i);
        }
    }
}

@include grid-x;
于 2018-09-04T10:52:42.123 回答