Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find the SCSS Index of the element in the list?

Iam working on SCSS Loops and got stuck with a problem. The Problem is consider a list of colors.

$colors:'red','green','red','blue';

@each $color in $colors{
  $i:index($colors,$color);
  .cube:nth-child(#{$i}){
    background:$color;
  };
}

The Output of the above program is

.cube:nth-child(1) {
  background: "red";
}

.cube:nth-child(2) {
  background: "green";
}

.cube:nth-child(1) { // issue here unable to get index value 3
  background: "red"; 
}

.cube:nth-child(4) {
  background: "blue";
}

I am unable to get the index value 3. Can Someone help me to solve this issue. My question is

  1. how to get the index value of 3?
  2. Is it possible to get the index using each? if "YES" how?
  3. If not what's the alternative way?
like image 362
Chandra Shekhar Avatar asked Oct 21 '25 20:10

Chandra Shekhar


1 Answers

This is what you need:

$colors:'red','green','red','blue';

@for $i from 1 through length($colors) {
  $color: nth($colors, $i);
  .cube:nth-child(#{$i}){
    background:$color;
  };
}

Your's fails cause index($colors,$color) will return always the first position of the element: Read ->http://sass-lang.com/documentation/Sass/Script/Functions.html#index-instance_method

like image 96
Dinca Adrian Avatar answered Oct 23 '25 11:10

Dinca Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!