1

I have a mixin for a gradient that currently takes two colors:

@mixin gradient($color-start, $color-end) {
  background-image: linear-gradient(90deg, $color-start 0%, $color-end 100%);
}

which I use everywhere like so

.my-gradient {
  @include gradient(blue, yellow)
}

but now I'd like to modify the mixin (or convert it to a function) that can take two or three parameters for the gradient.

something like (pseudo code):

@mixin gradient($color-start, $color-end, $color-center) {
  ...if $color-center param exists...
  background-image: linear-gradient(90deg, $color-start 0%, $color-center 50%, $color-end 100%);
  ...if $color-center param does not exist...
  background-image: linear-gradient(90deg, $color-start 0%, $color-end 100%);
}

I'm not sure of the best way to handle this condition.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Steve
  • 14,401
  • 35
  • 125
  • 230

1 Answers1

1

You can write if-else clauses in your mixin!

@mixin gradient($color-start, $color-end, $color-center:null) {
  @if($color-center){
       background-image: linear-gradient(90deg, $color-start 0%, $color-center 50%, $color-end 100%);  
  }@else{
       background-image: linear-gradient(90deg, $color-start 0%, $color-end 100%);    
  }

}

.test_1{
  @include gradient(#000, #111);
}

.test_2{
  @include gradient(#111,#222,#333);
}

outputs:

.test_1 {
  background-image: linear-gradient(90deg, #000 0%, #111 100%);
}

.test_2 {
  background-image: linear-gradient(90deg, #111 0%, #333 50%, #222 100%);
}

note that i set the parameter value of $color-centerto null otherwise there would be an error if you only pass 2 arguments

rebecca
  • 943
  • 9
  • 12