【问题标题】:SCSS function with for loop inside not working内部带有 for 循环的 SCSS 函数不起作用
【发布时间】:2018-07-29 04:08:29
【问题描述】:

我正在尝试编写一个函数,该函数基于 Sass(s​​css 语法)中的多种排列(而不仅仅是 12 列网格)创建网格布局。内部的 for 循环本身可以正常工作,但是当我将它包装在一个函数中时,它就不再工作了。我是使用 Sass 函数的新手,所以也许我弄乱了语法?或者这是不可能的?我只是想避免为我想要实现的每个布局编写一个新的 for 循环。提前致谢。

@function create-grid($num-cols) {
  @for $col from 1 through $num-cols {
    .col-#{$col}-of-#{$num-cols} {
      width: percentage($col / $num-cols);
    }
  }
}

【问题讨论】:

    标签: css function for-loop sass


    【解决方案1】:

    Sass 函数返回一个值。

    如果你想像这样以编程方式生成 css,你想使用 mixin。

    https://www.sitepoint.com/sass-basics-the-mixin-directive/

    @mixin grid($num-cols) {
      @for $col from 1 through $num-cols {
        .col-#{$col}-of-#{$num-cols} {
          width: percentage($col / $num-cols);
        }
      }
    }
    
    @include grid(12)
    

    【讨论】:

    • 哇,谢谢。我看到我可以在 Sass 中使用函数并直接使用它,而无需阅读有关 mixins 的内容。
    【解决方案2】:

    对于任何偶然发现这篇文章的人,最终产品是:

    @mixin create-grid($num-cols, $col-gutter) {
      @for $col from 1 through $num-cols {
        .col-#{$col}-of-#{$num-cols} {
          width: calc(
            ((100% - ((#{$num-cols} - 1) * #{$col-gutter})) / #{$num-cols}) *
              #{$col} +
              ((#{$col} - 1) * #{$col-gutter})
          );
        }
      }
    }
    

    非常感谢@HorusKol 向我介绍了 mixins 的世界!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      相关资源
      最近更新 更多