Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to dry up sass mixin code with before and after blocks?

Tags:

css

sass

mixins

dry

I have the following scss code.

  @if $position == bottom {
    &:after {
      height: $triangle-width;
      width: $triangle-width;
      content:"";
      position:absolute;
      margin-top: -$triangle-width/2 -$stroke-width;
    }
  }

  @if $position == top {
    &:before {
      height: $triangle-width;
      width: $triangle-width;
      content:"";
      position:absolute;
      margin-bottom: -$triangle-width/2 -$stroke-width;
    }
  }

As you can see, there is some code which is duplicated. I was wondering if there is a way to dry it up. I tried to put it into a own class but that didn't seem to work somehow. Any ideas? I could make a mixin in a mixin but that seems ab it too much overhead in my opinion. What do you think?

like image 945
dom Avatar asked Mar 16 '23 22:03

dom


1 Answers

Usually the best way to make things DRY is to break the common parts out into mixins and build those up into larger mixins. This is exactly how Compass and most other frameworks do this. See the Compass list mixins for example.

@mixin base-triangle($triangle-width) {
  height: $triangle-width;
  width: $triangle-width;
  content:"";
  position:absolute;
}

@mixin triangle($position, $triangle-width: 4, $stroke-width: 4) {
  @if $position == bottom {
    &:after {
      @include base-triangle($triangle-width);
      margin-top: -$triangle-width/2 -$stroke-width;
    }
  }

  @if $position == top {
    &:before {
      @include base-triangle($triangle-width);
      margin-bottom: -$triangle-width/2 -$stroke-width;
    }
  }
}

.foo {
  @include triangle("top", 8px, 8px);
}

.bar {
  @include triangle("bottom");
}

Compiles to:

.foo:before {
  height: 8px;
  width: 8px;
  content: "";
  position: absolute;
  margin-bottom: -12px;
}

.bar:after {
  height: 4;
  width: 4;
  content: "";
  position: absolute;
  margin-top: -6;
}
like image 177
steveax Avatar answered Apr 26 '23 00:04

steveax