SASS:如何在@each或@for中打印出`&`n次

时间:2014-10-01 04:16:24

标签: sass iterator css-preprocessor

我的SCSS中有以下循环:

@for $i from 1 to 5 {
    .thing-#{$i} {
        @if $i == 1 {
            & + & { /* some styles */ }
        }

        @if $i == 2 {
            & + & + & { /* some styles */ }
        }

        @if $i == 3 {
            & + & + & + & { /* some styles */ }
        }

        @if $i == 4 {
            & + & + & + & + & { /* some styles */ }
        }
    }
}

如何使用内置的SASS函数使代码以编程方式构建& + &行?

算法将是:

& + ((+ &) * $i) { /* styles */ }

1 个答案:

答案 0 :(得分:9)

您无法使用此语法实现每个函数,您将会遇到此语法错误Invalid CSS after "@each $i ": expected "in", was "from 1 to 5 {"。您应该使用for功能。

如果将此功能转换为算法,则每个步骤的样式都会相同。如果您想要这样的东西,可以尝试以下方法:

$var: #{"&"};

@for $i from 1 to 5 {

  .thing-#{$i} {
    #{append($var, #{"+ &"})} {
      color: red;
    }
  }

  $var: append($var, #{"+ &"});
}

输出

.thing-1 + .thing-1 {
  color: red;
}

.thing-2 + .thing-2 + .thing-2 {
  color: red;
}

.thing-3 + .thing-3 + .thing-3 + .thing-3 {
  color: red;
}

.thing-4 + .thing-4 + .thing-4 + .thing-4 + .thing-4 {
  color: red;
}

示例:http://sassmeister.com/gist/84189d6ae6c5a342668e