Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create hard-stop backgrounds in SASS/SCSS?

I've created a gradient that has 11 hard stops, creating the illusion of 11 separate boxes.

enter image description here

As it stands now, there's a % of the width hard-coded into the linear gradient. I can't help but think there's a much more efficient way (via SCSS?) rather than coding this out as such:

.color-bar {
      background: linear-gradient( to left,
        rgba(0, 0, 0, 0) 0%,
        rgba(0, 0, 0, 0) 9.09%,
        rgba(0, 0, 0, .1) 9.09%,
        rgba(0, 0, 0, .1) 18.18%,
        rgba(0, 0, 0, .2) 18.18%,
        rgba(0, 0, 0, .2) 27.27%,
        rgba(0, 0, 0, .3) 27.27%,
        rgba(0, 0, 0, .3) 36.36%,
        rgba(0, 0, 0, .4) 36.36%,
        rgba(0, 0, 0, .4) 45.45%,
        rgba(0, 0, 0, .5) 45.45%,
        rgba(0, 0, 0, .5) 54.54%,
        rgba(0, 0, 0, .6) 54.54%,
        rgba(0, 0, 0, .6) 63.63%,
        rgba(0, 0, 0, .7) 63.63%,
        rgba(0, 0, 0, .7) 72.72%,
        rgba(0, 0, 0, .8) 72.72%,
        rgba(0, 0, 0, .8) 81.81%,
        rgba(0, 0, 0, .9) 81.81%,
        rgba(0, 0, 0, 1) 90.09%,
        rgba(0, 0, 0, 1) 100%);
      height: 50px;
      width: 550px;
}
<div class="color-bar"></div>

Here's a rough Codepen in action.

Thanks for any input you can provide.

like image 454
Joe W. Avatar asked Apr 04 '17 14:04

Joe W.


1 Answers

Took me a bit of fiddling, but here it is:

@function hard-stops($direction, $from, $to, $steps) {
  $output: unquote("linear-gradient(") + $direction;
  @for $i from 0 through $steps {
    $output: $output + ', ' 
                     + mix($from, $to, $i*100/$steps) + ' ' 
                     + percentage($i/($steps+1)) + ', '
                     + mix($from, $to, $i*100/$steps) + ' ' 
                     + percentage(($i+1)/($steps+1));
  }
  $output: $output + ')';

  @return $output;
}
.color-bar {
  height: 50px;
  width: 550px;
  background: hard-stops(to left, rgba(0,0,0,1), rgba(0,0,0,0), 10);
}

jsFiddle.

The limitation is: one needs to pass mix-able colors (black, for example, is not, no idea why - I'm not much of an expert in sass).

like image 97
tao Avatar answered Oct 24 '22 02:10

tao