如何在SASS / SCSS中创建硬件背景?

时间:2017-04-04 14:20:13

标签: css sass linear-gradients

我创建了一个有11个硬停止的渐变,创造了11个独立框的幻觉。

enter image description here

现在,有一个宽度的百分比被硬编码成线性渐变。我不禁想到有一种更有效的方式(通过SCSS?)而不是这样编码:

.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.

感谢您提供的任何输入。

1 个答案:

答案 0 :(得分:3)

让我有点摆弄,但现在是:

@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

限制是:需要传递可混合的颜色(black,例如,不是,不知道为什么 - 我不是sass中的专家。