There is such a code

.image position: relative @for $i from 0 to 7 &:nth-child(#{$i + 1}) &:before content: '' @include sprite($advantages-$i) 

I want to use a loop, in it @include sprite($advantages-1) will return styles for the image from the sprite. How to use variables correctly, so that at each iteration of the loop I would get @include sprite($advantages-1) , @include sprite($advantages-2) , etc.?

  • Do you have somewhere declared $advantages-1 , $advantages-2 and so on? - Vitaliy Emelyantsev
  • That is, do you want in your code to dynamically generate variable names from which to take values? If so, Sass cannot do that. But the same can be done through Sass Maps: sitepoint.com/using-sass-maps - Vitaly Emelyantsev
  • Variables are declared in the file with styles and mixin for sprite. And yes, I'm trying to do a variable name generation in a loop. I want to figure it out. If it doesn't, describe the solution or share any information using Sass Maps. - korg
  • wrote. See if the answer came up to you, if I understood the conditions correctly. - Vitaly Emelyantsev

1 answer 1

Get the values ​​of dynamically generated variables - Sass does not allow. But you can solve the issue through Sass Maps:

 @mixin sprite($index) { background: url($index); } $advantages: 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg'; .image { position: relative; @for $i from 1 to length($advantages) { &:nth-child(#{$i}) { &::before { @include sprite(nth($advantages, $i)); content: ''; } } } } 

$advantages in this case is an array (but maybe a hash if necessary). In a loop through nth($advantages, $i) we get the value of a certain element of the array, and pass it as a parameter to the sprite mixin.

View code on Sassmeister .

  • I thank the kind person for knowledge! - korg