2

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);
Community
  • 1
  • 1
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239

1 Answers1

4

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

Vangel Tzo
  • 8,885
  • 3
  • 26
  • 32
  • Thanks! Could you explain a bit? What does `:""` do in the mixin? – Bram Vanroy Oct 15 '14 at 13:00
  • 1
    @BramVanroy `:""` means that it's an empty optional variable (variable doesn't exist). So if the $direction != (is not) empty use $direction variable else ignore it. Hope that this helped :) – Vangel Tzo Oct 15 '14 at 13:20