Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in SCSS with a combination of variables [duplicate]

Tags:

html

css

sass

I've got a bunch of elements: (#cp1, #cp2, #cp3, #cp4)

that I want to add a background colour to using SCSS.

My code is:

$colour1: rgb(255,255,255); // white $colour2: rgb(255,0,0); // red $colour3: rgb(135,206,250); // sky blue $colour4: rgb(255,255,0);   // yellow  @for $i from 1 through 4 {     #cp#{i} {         background-color: rgba($(colour#{i}), 0.6);          &:hover {             background-color: rgba($(colour#{i}), 1);             cursor: pointer;         }     } } 
like image 291
tobyn Avatar asked May 13 '12 08:05

tobyn


People also ask

Can we use for loop in SCSS?

Sass has several loop options, much like other programming languages. They include the @for loop, @each loop and @while loop. These loops are an incredibly powerful tool for generating CSS code because you can defer code generation into an iterable task.

Can SCSS variable change dynamically?

We can dynamically update SCSS variables using ReactJS with the help of a project by achieving theme switching of the card component between light and dark theme.

How to use each in SASS?

If you have a list of lists, you can use @each to automatically assign variables to each of the values from the inner lists by writing it @each <variable...> in <expression> { ... } . This is known as destructuring, since the variables match the structure of the inner lists.

What is Loop in sass?

sass Loops and Conditons Each loopThe @each directive allows you to iterate through any list or map. It takes the form of @each $var or <list or map> {} where $var can be any variable name and <list or map> can be anything that returns a list or map.


1 Answers

Instead of generating the variables names using interpolation you can create a list and use the nth method to get the values. For the interpolation to work the syntax should be #{$i}, as mentioned by hopper.

$colour1: rgb(255,255,255); // white $colour2: rgb(255,0,0); // red $colour3: rgb(135,206,250); // sky blue $colour4: rgb(255,255,0);   // yellow  $colors: $colour1, $colour2, $colour3, $colour4;  @for $i from 1 through length($colors) {     #cp#{$i} {         background-color: rgba(nth($colors, $i), 0.6);          &:hover {             background-color: rgba(nth($colors, $i), 1);             cursor: pointer;         }     } } 
like image 107
Xabriel Avatar answered Oct 31 '22 19:10

Xabriel