sass – 2 colors gradient mixin with fallback


// calculate the middle color for fallback
@mixin middle-color($c1, $c2)
  background-color: rgb((red($c1) + red($c2)) / 2, (green($c1) + green($c2)) / 2, (blue($c1) + blue($c2)) / 2)

// generate linear-gradient
@mixin linear-gradient($angle, $c1, $c2, $fallback: "")
  // background color fallback
  @if ($fallback !== "")
    background-color: $fallback
  @else
    @include middle-color($c1, $c2)
  // webkit linear gradient fallback
  @if $angle == to bottom
    background-image: -webkit-linear-gradient(top, $c1, $c2)
  @else if $angle == to right
    background-image: -webkit-linear-gradient(left, $c1, $c2)
  background-image: linear-gradient($angle, $c1, $c2)

Don’t use mix($c, $c2) to get the middle color!
It will only retrun ($c1 + $c2) / 2, not the middle color.
Sadly, I failed to put color stop percentage in the mixin.
Only if sass rgb() could return a color(e.g. #fff) from a string(e.g. “#fff 10%”).

,