Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out `&` n times in @each or @for

Tags:

iterator

sass

I have the following loop in my 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 */ }
        }
    }
}

How can I use the in-built SASS functions to make the code build the lines with the & + & programatically?

The algorithm would be:

& + ((+ &) * $i) { /* styles */ }
like image 939
Bryce Avatar asked Oct 01 '14 04:10

Bryce


1 Answers

You can't implement each function with this syntax, you will come up with this syntax error Invalid CSS after "@each $i ": expected "in", was "from 1 to 5 {". You should use for function.

If you convert this function to an algorithm you will come with the same styles for each step. If you would like something like that you could try the following:

$var: #{"&"};

@for $i from 1 to 5 {

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

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

The output will be

.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;
}

An example: http://sassmeister.com/gist/84189d6ae6c5a342668e

like image 70
Vangel Tzo Avatar answered Sep 20 '22 14:09

Vangel Tzo