nerdarama
nerdarama

Reputation: 493

Sass - @extend mixin, change an argument

I'm new to Sass, so if this isn't the best way of doing this type of thing, I apologise!

So, I've got a mixin for button style, like so:

@mixin button ($bg, $color, $padding, $display: inline, $radius: 0, $transition: 0.2s) {    
  background: $bg;
  @if $radius > 0 {
    @include border-radius($radius)
  }
  color: $color;
  @if $display != inline {
    display: $display;
  }
  @if $padding > 0 {
    padding: $padding;
  }
  text-decoration: none;
  @include transition(all, $transition, linear);
    &:hover {
        @if lightness($bg) > 50% {
          background: darken($bg, 10%);
        } @else {
          background: lighten($bg, 10%);
        }
    }
}

and a button, like so:

.btn {
   @include button(#095d94, #fff, 10px, inline-block);
}

But, now I need another button with a different background colour. So what I'm wondering is: is there a way to extend a class, and also just change an argument of the mixin that that class includes, without having to do this:

.btn2 {
  @extend .btn;
  background: #bad78d;
  &:hover {
      background: darken(#bad78d, 10%);
  }
}

Is it possible to feed in another background colour? Something like,

.btn2 {
    $bg: #bad78d; //i know this doesn't work
    @extend .btn;
}

or like,

.btn2 ($bg: #bad78d) {
   @extend .btn; //this one doesn't even make sense, but I think I'm explaining what I need... ish.
}

Upvotes: 1

Views: 297

Answers (1)

Nico O
Nico O

Reputation: 14102

I think you have two options here.

Also you try to keep it dry, there is nothing too wrong about repading sometimes. So if your mixin is not too huge it'll be ok to this:

    .btn {
       @include button(#095d94, #fff, 10px, inline-block);
    }

    .btn2 {
       @include button(#bad78d, #fff, 10px, inline-block);
    }

But This will only be required if the difference between .btn and .btn2 is big.

If you just want to change certain properties, you may also just use the classig cascading.

 .btn,.btn2 {
       @include button(#095d94, #fff, 10px, inline-block);
    }

.btn2 {
      background-color:#bad78d;   
      ...
    }

Upvotes: 1

Related Questions