使用scss从变量中向网格添加cols

时间:2019-05-29 05:53:24

标签: sass

是否可以通过变量来计算grid-template-columns中的cols数量?

我有一个变量$ num-of-cols:5;我用它来制作白色的scss类,并且效果很好,但是我也想使用相同的变量来为grid-template-columns生成cols。
像:grid-template-columns:[col-1] $ width-cols [col-2] $ width-cols [col-3] $ width-cols [col-4] $ width-cols [col-5] $ width-cols [col-6];
$ width-cols应该计算为100%/ $ num-of-cols- $ grid-gutter-width。 (名称很重要,从1到$ num-of-cols)。

$grid-gutter-width: 1rem;
$num-of-cols: 5;
$width-cols: calc(100%/#{$num-of-cols} - #{$grid-gutter-width});
.grid {
    display: grid;
    grid-gap: $grid-gutter-width;
    padding: $grid-gutter-width;
    padding-right: 0;
    grid-template-columns: [col-1] $width-cols [col-2] $width-cols [col-3] $width-cols [col-4] $width-cols [col-5] $width-cols [col-6];
    grid-template-rows: auto;
}

1 个答案:

答案 0 :(得分:0)

您可以使用mixin(或函数),例如:

SCSS

$grid-gutter-width: 1rem;
$num-of-cols: 5;
$width-cols: calc(100%/#{$num-of-cols} - #{$grid-gutter-width});
@mixin grid-template-columns {
    $columns: [col-1],;  // note trailing comma indicates list  
    @for $i from 2 through $num-of-cols + 1 {
        $columns: append($columns, $width-cols [col-#{$i}], space);
    }
    grid-template-columns: $columns;
}



.grid {
    display: grid;
    grid-gap: $grid-gutter-width;
    padding: $grid-gutter-width;
    padding-right: 0;
    @include grid-template-columns; // <= include 
    grid-template-rows: auto;
}

CSS

.grid {
  display: grid;
  grid-gap: 1rem;
  padding: 1rem;
  padding-right: 0;
  grid-template-columns: [col-1] calc(100%/5 - 1rem) [col-2] calc(100%/5 - 1rem) [col-3] calc(100%/5 - 1rem) [col-4] calc(100%/5 - 1rem) [col-5] calc(100%/5 - 1rem) [col-6];
  grid-template-rows: auto;
}