css - 如何用前后 block 干掉sass mixin代码?

标签 css sass dry 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;
    }
  }

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

最佳答案

通常,让事情变干的最好方法是将公共(public)部分分解为混入,然后将它们构建成更大的混入。这正是 Compass 和大多数其他框架的做法。查看Compass list mixins例如。

@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");
}

编译为:

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

.bar:after {
  height: 4;
  width: 4;
  content: "";
  position: absolute;
  margin-top: -6;
}

关于css - 如何用前后 block 干掉sass mixin代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30498142/

相关文章:

security - 如何在多个位置重复使用 NGINX 代理设置

css - 选择控件的 Bootstrap 跨浏览器问题

css - 带有 Bootstrap 的图片库

javascript - 如何使列表项滚动动画看起来连续/无限

sass - Laravel Elixir 不观看 gulp 的 SASS 导入文件

css - 我可以让这个 CSS 更简单以避免重复父选择器吗?

javascript - 在导航样式上使用 getElementById?

vue.js - 使用 SCSS 和 Vue 3 避免 v-deep 重复

css - 基金会 5 : enable button radii (radiuses) globally

ruby-on-rails - 如何使用元编程进行 DRY?