Html – For loop in SCSS with a combination of variables

csshtmlsass

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;
        }
    }
}

Best Solution

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;
        }
    }
}