条纹渐变混合器

Avatar of Kitty Giraudel
Kitty Giraudel

在 CSS 中绘制条纹的常用方法是定义一个带有重叠颜色停止点的线性渐变。它工作得很好,但手工编写起来并不方便……数十亿美元的想法:使用 Sass 从颜色列表中自动生成它!

/// Stripe builder
/// @author Kitty Giraudel
/// @param {Direction} $direction - Gradient direction
/// @param {List} $colors - List of colors
/// @output `background-image` if several colors, `background-color` if only one
@mixin stripes($direction, $colors) {
  $length: length($colors);
  
  @if $length > 1 {
    $stripes: ();
    
    @for $i from 1 through $length {
      $stripe: (100% / $length) * ($i - 1);
      
      @if $i > 1 {
        $stripes: append($stripes, nth($colors, $i - 1) $stripe, comma);
      }
      
      $stripes: append($stripes, nth($colors, $i) $stripe, comma);
    }
    
    background-image: linear-gradient($direction, $stripes);
  } @else if $length == 1 {
    background-color: $colors;
  }
}

用法

body {
  @include stripes(to right, #8e44ad #2c3e50 #2980b9 #16a085 #27ae60);
}