如何用块之前和之后干掉 sass mixin 代码?

dom*_*dom 4 css dry sass mixins

我有以下 scss 代码。

  @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;
    }
  }
Run Code Online (Sandbox Code Playgroud)

如您所见,有一些代码是重复的。我想知道有没有办法把它弄干。我试图把它放到一个自己的类中,但这似乎不起作用。有任何想法吗?我可以在 mixin 中创建一个 mixin,但在我看来这似乎是太多的开销。你怎么认为?

ste*_*eax 5

通常,使事情变得 DRY 的最佳方法是将公共部分分解为 mixin,然后将它们构建为更大的 mixin。这正是 Compass 和大多数其他框架执行此操作的方式。例如,请参阅Compass 列表 mixin

@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");
}
Run Code Online (Sandbox Code Playgroud)

编译为:

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

.bar:after {
  height: 4;
  width: 4;
  content: "";
  position: absolute;
  margin-top: -6;
}
Run Code Online (Sandbox Code Playgroud)