首页 > 解决方案 > 使用 SASS 的动态间距类

问题描述

大家好!

我正在使用一个 sass 文件,该文件具有一组用于填充和边距的硬编码帮助程序类。因为我们在scss这里工作,所以这是多余的,可以用 sass 函数或其他东西来解决。
我遇到的麻烦实际上是写花式sass来完成繁重的工作,因为这需要......数学。喘气


目前看起来是这样的……

// Spacing
$spacer: 1rem;

// Margin Helpers
.m-0 {margin: 0;}
.m-1 {margin: ($spacer * .25);}
.m-2 {margin: ($spacer * .5);}
.m-3 {margin: ($spacer);}
.m-4 {margin: ($spacer * 1.5);}
.m-5 {margin: ($spacer * 3);}

.mt-0 {margin-top: 0;}
.mt-1 {margin-top: ($spacer * .25);}
.mt-2 {margin-top: ($spacer * .5);}
.mt-3 {margin-top: ($spacer);}
.mt-4 {margin-top: ($spacer * 1.5);}
.mt-5 {margin-top: ($spacer * 3);}

.ml-0 {margin-left: 0;}
.ml-1 {margin-left: ($spacer * .25);}
.ml-2 {margin-left: ($spacer * .5);}
.ml-3 {margin-left: ($spacer);}
.ml-4 {margin-left: ($spacer * 1.5);}
.ml-5 {margin-left: ($spacer * 3);}

现在想象一下这个 ^^ 与每一边和间距,所有硬编码,并重复填充助手。是的,我的下巴也在地上。

我想把上面的混乱变成一个 sass 函数,mixin,任何适合这个难题的东西。我搜索了互联网的深处,发现了很多比必要的更复杂的东西,或者无法做我需要的数学。我对 scss 函数和 mixins 没有那么丰富的经验,所以不要欺负我。


我尝试了大约 3 个小时,直到我最终放弃;在此期间,我发现并正在阅读一些可能会有所帮助的文章,但我无法将我的大脑面条完全包裹起来,因此我将包括以下内容。

SASS 边距和填充助手循环。生成 .mt-10 类型的辅助类。

如何使用 SCSS 动态构建辅助类


如果你能帮我解决这个 sass 文件的耻辱,我会给你一个虚拟拥抱的巨大熊 :)


提前致谢!
〜乔什

标签: htmlcsssass

解决方案


这是一个非常简单的混合来做你想做的事:

@mixin generate($prefix, $property) {
  // List of sizes to generate for each
  $sizes: [0, .25, .5, 1, 1.5, 3];
  // Spacing to multiply the sizes by
  $spacing: 1rem;
  
  // Loop through all of the sizes(we use @for rather than @each, as we want access to the index)
  @for $i from 1 through length($sizes) {
    // Get the size for the current index
    $size: nth($sizes, $i);
    
    // Create the rule
    .#{$prefix}-#{$i - 1} {
      #{$property}: $spacing * $size;
    }
  }
}

这个 mixin 的用法如下所示:

@include generate(ml, margin-left);

并将编译为:

.ml-0 {
  margin-left: 0rem;
}

.ml-1 {
  margin-left: 0.25rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.ml-3 {
  margin-left: 1rem;
}

.ml-4 {
  margin-left: 1.5rem;
}

.ml-5 {
  margin-left: 3rem;
}

你可以玩弄这个 sassmeister

在为大量属性生成这些属性时,您可以再采取一步,并使用@each

$rules: [
  [ml, margin-left],
  [mt, margin-top],
  [mb, margin-bottom],
  [mr, margin-right],
];

@each $item in $rules {
  @include generate(nth($item, 1), nth($item, 2));
}

为了您的方便,还有另一个 sassmeister 。

虽然您可以更深入地遍历-top,-bottom等,因此您只需指定一个属性并生成其他所有内容,但我不知道您的用例,您可以弄清楚。


推荐阅读