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

时间:2018-09-04 10:29:43

标签: css css3 sass css-preprocessor scss-mixins

我有以下SCSS mixin,它可以生成从.grid1.grid12的CSS类:

$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获得所需的结果吗?

为便于测试,只需将混合包粘贴到sassmeister上。

2 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分: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;