Search code examples
csssassmixins

Create A Mixin With and Without Border


I'm trying to create a Mixin that takes one out of two variables and creates a filled button, or an outlined button depending on the variable passed.

@include button-style($color: red);

// would result in
background-color: transparent;
color: red;
box-shadow: inset 0 0 0 1px red;

@include button-style($bg: red);

// would result in
background-color: red;
color: white;

Is there a way to do this? I'm going crazy over here trying to work out the simplest way to achieve this. Here's what I've got so far.

@mixin button-style($bg: transparent, $color: white) {
  background-color: $bg;
  color: $color;
  @if $color == 'white' {
    box-shadow: inset 0 0 0 1px $color;
  }
}

Any help is appreciated. Thanks in advance!


Solution

  • This seems to work for me. I've set up an working example over here. The only drawback is I'm having to tie transparent to a variable like so:

    $transparent: transparent;
    
    @mixin button-style($bg: $transparent, $color: white) {
      background-color: $bg;
      color: $color;
      @if $bg == $transparent {
        box-shadow: inset 0 0 0 1px $color;
      }
    }
    
    .button-pri {
      @include button-style($bg: red);
    }
    
    .button-sec {
      @include button-style($color: red);
    }
    

    If possible I would like to cut that variable out of the equation and go straight for if $bg == 'transparent { ..., but that if statement doesn't seem to work with a string.

    Update

    Thanks to @KreaTief, apparently I don't need to use a variable. Updated answer below:

    @mixin button-style($bg: transparent, $color: white) {
      background-color: $bg;
      color: $color;
      @if $bg == transparent {
        box-shadow: inset 0 0 0 1px $color;
      }
    }
    
    .button-pri {
      @include button-style($bg: red);
    }
    
    .button-sec {
      @include button-style($color: red);
    }