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; } } }
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.
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.
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.
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.
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With