Sass: color change with @for loop

I am trying to darken a variable number of divs like enter image description here with the following code:

@mixin color-divs ($count, $baseName, $startcolor) { $color: $startcolor; @for $i from 0 through $count { $color: darken($color, 9%); ##{$baseName}_#{$i} { background-color:$color; } } } 

With this code, which I expected, the $ color variable changes with each iteration, but this did not work as expected. The value is fixed after the initial initialization, and each element has the same color.

Is there a way to solve this problem or is there another way to solve this problem when mixing?

+5
source share
3 answers

You can darken the color using $ i inside @for and apply the appropriate classes to the div. Hope this helps.

SCSS

 @mixin color-divs ($count, $baseName, $startcolor) { @for $i from 0 through $count { $background-color: darken($startcolor, $i * $i); .colored-div#{$i} { background: $background-color; height:100px; width:200px; float: left; margin-right: 5px; } } } @include color-divs(5,'a',#ffd8b1); 

HTML

 <div class="colored-div1">a</div> <div class="colored-div2">b</div> <div class="colored-div3">c</div> <div class="colored-div4">d</div> <div class="colored-div5">e</div> 

Demo

Watch the demo

+7
source

I created this example based on your mixin:

 @mixin color-divs ($count, $baseName, $startcolor) { $loop_color: $startcolor; @for $i from 0 through $count { $loop_color: darken($loop_color, 9%); .#{$baseName}-#{$i} { background-color: $loop_color; } } } div { width: 100px; height: 100px; float: left; } @include color-divs(6,'div',#faa) 

Used with the following markup:

 <div class="div-1"></div> <div class="div-2"></div> <div class="div-3"></div> <div class="div-4"></div> <div class="div-5"></div> <div class="div-6"></div> 

Exit: http://jsfiddle.net/jdtvF/

http://uk.omg.li/P0dF/by%20default%202013-05-16%20at%2010.10.43.png

 div { width: 100px; height: 100px; float: left; } .div-0 { background-color: #ff7c7c; } .div-1 { background-color: #ff4e4e; } .div-2 { background-color: #ff2020; } .div-3 { background-color: #f10000; } .div-4 { background-color: #c30000; } .div-5 { background-color: #960000; } .div-6 { background-color: #680000; } 
+2
source

To just go from one color to another, say, several consecutive <div> :

  @for $i from 0 through 11 &:nth-child(#{$i}) transform: rotate(#{30*$i}deg) background-color: mix($gray1, $gray2, $i / 12 * 100% ) 

Notes

  • Please note that you do not need #{…} inside mix() , because it is a sass function, so it is clear that any variables and calculations used inside must be enabled before turning them into CSS.
  • Conversion is just my use case (for demonstration). Here you need #{…}
  • and pay attention to the + / -1 issue (as in every for loop, in any language): transition from 0/12 to 11/12
  • finally turning it into a percentage to cater to the mixing features
0
source

All Articles