Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCSS/SASS list reverse iteration (backward loop)

Tags:

sass

Reversing the order of a @for iteration output in SCSS can be done as so:

SCSS example: GIST DEMO

$colors : green, gold, red;

a{
  $i : length($colors);
  @each $c in $colors {
      &:nth-child(#{$i}){
           fill:$c;
      }
      $i : $i - 1;
  }
}

Output:

a:nth-child(3) {
  fill: green;
}
a:nth-child(2) {
  fill: gold;
}
a:nth-child(1) {
  fill: red;
}

Is this the best way of SASS reverse iterating?

Does anyone know of a more "SCSS native" way of achieving this goal which increases readability?

like image 835
vsync Avatar asked Oct 29 '22 10:10

vsync


1 Answers

Your solution is ok.

You can create a function that will reverse your array:

@function reverse($list, $recursive: false) {
   $result: ();

   @for $i from length($list)*-1 through -1 {
      @if type-of(nth($list, abs($i))) == list and $recursive {
        $result: append($result, reverse(nth($list, abs($i)), $recursive));      
      }

      @else {
        $result: append($result, nth($list, abs($i)));
      }
   }

   @return $result;
}

$list: #aaa, #bbb, #ccc, #ddd;
$new-list: reverse($list);

@for $i from 1 through length($new-list){
  div:nth-child(#{$i}){
    color: nth($new-list, $i);
  }
}

You can use nth-last-child selector.

@for $i from 1 through length($list){
  div:nth-last-child(#{$i}){
    color: nth($list, $i);
  }
}

You can rewrite your array: $list: #ddd, #aaa, #bbb, #ccc and use nth-child.

like image 79
3rdthemagical Avatar answered Jan 02 '23 21:01

3rdthemagical