Search code examples
htmlcsssassmixins

Prevent Sass from including property at all


In my current project I use a sass-mixin roughly like this:

mixin.scss:

@mixin my_mixin($header-border-top-stack, 
                $header-border-bottom-stack) {
  #some-id {
     border-top: $header-border-top-stack;
     border-bottom: $header-border-top-stack;
  }
}

styles.scss:

@import "path/to/mixin.scss";
@include my_mixin(1px solid black, 2px solid red);

Sometimes I don't want to touch the border-bottom property at all. Sadly this:

@import "path/to/mixin.scss";
@include my_mixin(1px solid black, none);

results in .css like this:

#some-id {
  border-top: 1px solid black;
  border-bottom: none;
}

I'm looking for a way to prevent the mixing from touching the border-bottom property at all (don't even include it in the .css). Any ideas?


Solution

  • I added an @if condition for the check

    @mixin my_mixin($header-border-top-stack, $header-border-bottom-stack) {
      #some-id {
        border-top: $header-border-top-stack;
        @if $header-border-bottom-stack != 'none' {
          border-bottom: $header-border-bottom-stack;
        }
      }
    }
    

    This works fine. However just a tip, I noticed that you're mixin places the selector inside it which isn't flexible and I don't know if that's good practice. You could rewrite it this way

    @mixin my_mixin($header-border-top-stack, $header-border-bottom-stack) {
      border-top: $header-border-top-stack;
      @if $header-border-bottom-stack != 'none' {
        border-bottom: $header-border-bottom-stack;
      }
    }
    

    By doing this you're mixin can be used on different tags
    div { @include my_mixin(1px solid black, none); }
    p { @include my_mixin(1px solid black, 2px solid red); }

    instead of it always returning #some-id { ... }