question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Setting SASS variables inside a loop

See original GitHub issue

I am having problems putting something like the following repetitive variable declarations inside a loop:

$px1: 1px;
$px2: 2px;
$px3: 3px;
$px4: 4px;
$px5: 5px;
...

I thought i could just do this:

@for $i from 1 through 10 {
  $px#{$i}: #{$i}px;
}

But SCSS is complaining that it is invalid CSS, but i am not trying to write CSS, i am just trying to set some variables that i can use later on.

Is there a way to set variables dynamically like this, without declaring any CSS?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:6

github_iconTop GitHub Comments

7reactions
xzyfercommented, May 4, 2016

To do this you need a list

$pxs: ();
@for $i from 1 through 10 {
  $pxs: append($pxs, $i * 1px);
}

Now you can access you px via nth

a {
  border-width: nth($pxs, 1); // 1px
}

1reaction
wouter-mullercommented, May 4, 2016

OK, thanks guys!

@xzyfer Interesting example with the list!

I will only need a handful of these variables, so i’ll just write them out without a loop…

Read more comments on GitHub >

github_iconTop Results From Across the Web

SCSS / SASS : How to create variables inside an each loop
In my SASS code I have an array with all my colours, then I made an each loop to create css variables from...
Read more >
Sass: @for
Each number along the way is assigned to the given variable name. If to is used, the final number is excluded; if through...
Read more >
Use loops in Sass to streamline your code - OpenClassrooms
A loop is just repeating a set of actions on items in a collection until ... These variables exist only within that iteration...
Read more >
Looping with SCSS - Pixel Pixel
To use variables in concatenation or in an expression, you'll need to use interpolation (similar to ES6 template literals or PHP interpolation) by...
Read more >
Sass/SCSS for, each & while loops (Iteration Control) Tutorial
In this Sass/SCSS tutorial we learn how to control the flow of our script and repeat sections of code with loops. We cover...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found