xeho91 xeho91 - 1 year ago 72
CSS Question

Loop in Sass @for how to use $#{value}#{$i} correctly?

I am still learning in front-end developing and I got stuck in Sass with Loop @for.

So, let me show the code firstly and below I will explain what I am trying to achieve.

$menu-items-1lvl-quantity: 3; // How many items will be on first level of menu list?
$menu-icon-item1: "\f007"; // The icon for first menu item on first level
$menu-icon-item2: "\f07c"; // The icon for second menu item on first level
$menu-icon-item3: "\f1fa"; // The icon for second menu item on first level

@for $i from 1 through $menu-items-1lvl {
.#{menu-item}#{$i}:before {
content: $#{menu-icon-item}#{$i};

So, I want this loop to create for each class of "menu-item1:before, menu-item2:before, menu-item3:before to add propery content: with values described in variables above.
I want it to add as value to each property of content $menu-icon-item1, $menu-icon-item2, $menu-icon-item3.

I have read the documentation on sass official site, but it seems I couldn't find an example to what I want to achieve.

So, I got confused in trying to figure out what is wrong with my code or what wrong I am doing.
I would like to know if it is even possible what I am trying to achieve with @for loop in this case. Or should I use different loop? Could anyone please advice me?

Below is the Error log message I get from Git for WIndows console using gulp-sass.

Error: Invalid CSS after "... content:": expected expression (e.g. 1px, bold), was "$#{menu-icon-item}#"
on line 79 of www/StyleSheets/Sass/Layout/_menu.scss

content: $#{menu-icon-item}#{$i};


Answer Source

You can set a variable of $menu-icon-items:"\f007","\f07c","\f1fa"; and loop through using its length, see example here:


<div class="menu-item1">1</div>
<div class="menu-item2">2</div>
<div class="menu-item3">3</div>


  @for $i from 1 through length($menu-icon-items) {
      &:before {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download