Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass @for loop - from one color to another color

Tags:

css

for-loop

sass

I need to create a list of css background colors gradually getting darker to reach a destination darkness. I know it's possible to use the technique stated here: Sass: Change color with @for loop But what I want to modulate from one color to another color. Not just make the color darker and darker.

I have a variable number of items and would like the background color to move from white to black. Basically a stepped gradient with a beginning and end color defined.

So if I had three items I would want the output to be something like this:

.class1 {
  background-color: #fff;
}
.class2 {
  background-color: #808080; // 50% brightness
}
.class3 {
  background-color: #000;
}

If I had five items it would look something like this:

.class1 {
  background-color: #fff;
}
.class2 {
  background-color: #bfbfbf; // 75% brightness
}
.class3 {
  background-color: #808080; // 50% brightness
}
.class4 {
  background-color: #404040; // 25% brightness
}
.class5 {
  background-color: #000;
}

The beginning and ending colors should always be the same, but the middle colors need to automatically adjust depending on the total of items in the loop.

I don't know if something like this is even possible with Sass??

like image 312
NateW Avatar asked May 27 '15 15:05

NateW


1 Answers

The function you're needing here is mix();

$color-1: white;
$color-2: black;

$steps: 5;

@for $i from 0 to $steps {
    .class-#{$i + 1} {
        background: mix($color-1, $color-2, percentage($i / ($steps - 1)));
    }
}

Output:

.class-1 {
  background: black;
}

.class-2 {
  background: #3f3f3f;
}

.class-3 {
  background: #7f7f7f;
}

.class-4 {
  background: #bfbfbf;
}

.class-5 {
  background: white;
}

http://sassmeister.com/gist/d0fc452765908aac2617

Want them in the reverse order? Just swap the colors.

like image 181
cimmanon Avatar answered Oct 11 '22 22:10

cimmanon