SASS/SCSS mixin 生成 css 网格 类 - IE 11 需要额外的 20px 间隙列

SASS/SCSS mixin to generate css grid classes - need additional 20px gap columns for IE 11

我有以下 SCSS mixin,它生成 CSS 类 从 .grid1.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

您可以为间隙包含另一个变量,然后像这样操作。

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

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

我可以使用 @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;