2

Imagine I have the following set of defined variables:

$sportmenu_1: #23765c;
$sportmenu_3: #5e6b34;
$sportmenu_4: #7d7e6c;
$sportmenu_6: #786857;
$sportmenu_8: #487a91;

I also have a list containing the "id" or the last digit of each variable as:

$list: 1 3 4 6 8;

I then want to the $sportmenu_ variables to both name the css selectors and populate the properties, I'm using a list and a foreach as follows:

@each $id in $list_id_sports {

  #sportmenu_#{$id} { //this works fine
    .menu-sport-item {
      background-color: #{$sportmenu_}#{$id}; //here's the issue!
    }
  }
}

The problem is that I cannot find a way to combine a string and the $id from the foreach to generate a variable that the Sass compiler will understand. Basically, I want the foreach to create a new variable by combining $sportmenu_ and the value of $id. Not sure if this is possible.

My solution doesn't work, since $sportmenu_ doesn't exist. I've tried combining a string and the $id as: "$sportmenu_"#{$id} but this just creates a string followed by the value of $id.

Thanks!

1 Answer 1

1

Why can't you do something like this? Using maps

$list: (1: #23765c, 3: #5e6b34, 4: #7d7e6c, 6: #786857, 8: #487a91);

//$id grabs your map index, and $val grabs your hex color values
@each $id, $val in $list {
  #sportmenu_#{$id} {
    .menu-sport-item {
      background-color: #{$val};
    }
  }
}

You can try it out on SassMeister. Which outputs :

#sportmenu_1 .menu-sport-item {
  background-color: #23765c;
}

.....

All I am doing over here is nothing but using maps(kind of hash), looping over, and printing colors accordingly.


Also, what you were trying won't work. You are trying to interpolate two variables and trying to create a dynamic variable name on compile.

#{$sportmenu_}#{$id}; //will throw undefined $sprotsmenu_ error
Sign up to request clarification or add additional context in comments.

3 Comments

Yup, this is exactly the solution I ended up implementing, when I mean exactly is exaaactly haha. However, I'm still intrigued if there is a way to achieve what I wanted in the first place.
@ObedMarquezParlapiano As far as I know, there isn't any.
Cheers buddy, will accept your answer as accepted, solves the problem after all :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.