我正在使用一个sass文件,该文件具有一组looooooong硬编码的辅助类,用于填充和边距。因为我们在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函数和mixin经验不足,所以现在还不要欺负我。
我尝试了大约3个小时,直到我最终放弃。在此期间,我已经找到并正在阅读一些可能会有所帮助的文章,但我无法将我的脑筋包住,所以下面将在其中列出。
SASS保证金和填充助手循环。生成.mt-10类型的帮助程序类。
如果您能帮助我解决Sass文件的这种耻辱,我会给您一个虚拟拥抱的巨大熊:)
提前致谢!
〜乔希
这是一个非常简单的mixin,可以执行您想要的操作:
@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;
}
如果要为大量属性生成这些属性,则可以采取另一步骤,并使用@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));
}
为了您的方便,另辟s径。
虽然你可以去更深,在刚刚循环-top
,-bottom
等等,所以你只需要指定属性,并产生一切,我不知道你使用的情况下,你自己看着办吧。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句