Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass: Change color with @for loop

Tags:

css

for-loop

sass

I try to darken a variable number of divs like that enter image description here with 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 that code I was expecting, that the variable $color is changed with every iteration but this didn't work as expected. The value is fix after the fist initialisation and every element has the same color.

Is there a way to workarround that problem or is there another way to solve that problem with a mixing?

like image 803
crashbus Avatar asked May 16 '13 08:05

crashbus


2 Answers

You can darken the color using $i inside @for and apply respective classes to the divs. 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

See demo

like image 57
anpsmn Avatar answered Sep 29 '22 07:09

anpsmn


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>

Output: 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; }
like image 29
omgmog Avatar answered Sep 29 '22 08:09

omgmog