Nash
Nash

Reputation: 562

Sass each loop with an index

So I'm trying to get an index in my each loop. Is this possible. Here is my code:

@each $food, $tons-produced in $top-foods {
  $i: index($top-foods, $food);
  rect:nth-child(#{$i + 1}){

  }
}

Which is returning a "Invalid null operation: 'null plus 1'."

So its not indexing and $i is null.

I've also tried $i: index($top-foods, ($food, tons-produced));

Here is my list I'm eaching through:

$top-foods: ("Sugar Cane" 1898),
("Corn" 1017),
("Rice" 738),
("Wheat" 711),
("Cow Milk" 635),
("Potatoes" 374),
("Vegetables" 279),
("Soy Beans" 278),
("Cassava" 263),
("Sugar Beets" 247);

Upvotes: 1

Views: 2881

Answers (2)

Zankar
Zankar

Reputation: 248

Here's my take on the problem.

$vals : (
  (32px, $red, 8%, 90%)
  (18px, $red, 18%, 46%)
  (48px, $yellow, 25%, 97%)
  (40px, $red, 26%, 30%)
);

@for $i from 1 through length($vals) {
    $val : nth($vals, $i); // <-- store the current item in a variable
    .items .nth-#{$i} {
        width: #{nth($val, 1)}; // <-- reference item's values
        height: #{nth($val, 1)};
        background-color: #{nth($val, 2)};
        left: #{nth($val, 3)};
        top: #{nth($val, 4)};
    }
}

This worked wonderfully in my case

Upvotes: 0

user4994625
user4994625

Reputation:

I'm not sure if I understand you, this is you want to do more of less?:

@for $i from 1 through length($top-foods){
  selector:nth-child(#{$i}){
    display:block;
  }
}

http://www.sassmeister.com/gist/fc9cf973e81c80c496e3d6111e62bce5

UPDATE

I can't get the index with multiple values in @each loop. Try using a single value. And you can't do an addition inside nth-child(), do it before.

@each $food in $top-foods {
  $i: index($top-foods, $food);
  $i: $i + 1;
  rect:nth-child(#{$i}){
    display: block;
  }
}

http://www.sassmeister.com/gist/c00a1b1577166dbf4a711426604b2f54

Upvotes: 1

Related Questions