【问题标题】:Produce whitespace-free CSS string with SASS @while loop使用 SASS @while 循环生成无空格的 CSS 字符串
【发布时间】:2014-03-20 03:03:10
【问题描述】:

我正在尝试编写一个将字符串作为选择器的一部分重复的 mixin。我想要的输出对空格非常敏感,但是如果不引入所述空格,我找不到使 SASS 编译的方法。

期望的输出是:

body:nth-child(n):nth-child(n){
  background: blue;
}

body:nth-child(n){
  background: green;
}

body {
  background: red;
}

我想用这个调用来实现它:

body {
  @include increase-specificity( 2 ){
    background: blue;
  }

  @include increase-specificity{
    background: green;
  }

  background: red;
}

问题是:nth-child(n) 字符串在当前选择器 (&) 之后或重复之间不能接受任何空格,之后不更改功能性 CSS——而且我找不到编写mixin 实现了这一点而不会导致 SASS 错误。

这就是我尝试表达 mixin 的方式:

@mixin increase-specificity( $depth: 1 ){
  &@while($depth > 0){#{'nth-child(n)'}$depth: $depth-1}{
    @content;
  }
}

And here's a Codepen to show it breaking.

到目前为止我的问题是:

  • SASS 不会容忍紧跟在 & (&@while{...) 之后的 @while 循环,但我想不出任何其他方法来避免编译字符串之间出现空格。
  • 同样,如果不使用空格,我无法找到编写函数式@while 循环的方法:当前语法在到达插值器(#{…})的末尾时会失效(不知道为什么),但删除插值会导致它在尝试解释 nth-child 的括号时出错。

【问题讨论】:

    标签: css sass mixins


    【解决方案1】:

    您的代码中有很多错误(错误的逻辑、缺少空格、不匹配的括号等),不值得尝试解释为什么它不起作用。

    @mixin increase-specificity( $depth: 1 ) {
      $sel: '';
      @while($depth > 0) {
        $sel: $sel + ':nth-child(n)';
        $depth: $depth - 1;
      }
      &#{$sel} {
        @content;
      }
    }
    
    body {
        @include increase-specificity( 2 ){
            background: blue;
        }
    
        @include increase-specificity{
            background: green;
        }
    
        background: red;
    }
    

    【讨论】:

    • 我怀疑解析错误是 因为 缺少空格,这首先是问题 - 没有它就无法简洁地表达 - 但是不匹配的括号把我扔了一点点。逻辑似乎没问题(我一直认为 Ruby 的重点是你不必进行变量赋值和冗长的连接等 - 但我想你需要空格!),但我会相信你的话 - 谢谢寻找可行的解决方案!
    • Sass 不是 Ruby,它只是一个用 Ruby编写的解析器。
    • 你是对的——相似之处是偶然的,并非指示性的。
    猜你喜欢
    • 2015-12-14
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多