Bram Vanroy
Bram Vanroy

Reputation: 28524

Making a SCSS mixin with an optional argument that is passed to the property name

I have been reading through a couple of answers but none of these help me where I need it.

I want to write a rule for borders that consist of three variables. The first is optional and makes clear which side the border should be on (top, right, bottom or left; if not present the default should simply be border:). The second one defines the width of the border and the latter the colour. I tried something like this. But that doesn't work unfortunately, because I don't provide a third argument I am guessing.

@mixin border($direction,$size,$colour) {
    @if variable-exists($direction) {
        border-#{$direction}: $size solid $colour;
    } @else {
        border: $size solid $colour;
    }
}
$borderradius: 2px;
$borderSize: 1px;
$mainColour: #ccc;
$hoverColour: #4679bd;

@include border($borderSize, $mainColour);

Upvotes: 2

Views: 2414

Answers (1)

Vangel Tzo
Vangel Tzo

Reputation: 9313

You could try this solution. By adding the optional variable at the end of your arguments. Keep in mind that you have to place the optional variable last in your arguments order.

@mixin border($size, $colour, $direction:"") {
  @if $direction != "" {
    border-#{$direction}: $size solid $colour;
  }

  @else {
    border: $size solid $colour;
  }
}

$borderradius: 2px;
$borderSize: 1px;
$mainColour: #ccc;
$hoverColour: #4679bd;

div {
  @include border($borderSize, $mainColour);
}

An example: http://sassmeister.com/gist/560cb13c92498d6d39e6

Upvotes: 4

Related Questions