Sass - 重复代码,我怎样才能使它更简洁

时间:2017-01-17 12:16:58

标签: sass

我正在创建帮助类,将颜色更改为预定义变量。在大多数情况下,代码是相同的。我将添加更多特定的选择器,如何使这更容易维护?

.fg-text {
  color: $colorText;
  button, .button,
  input[type="button"],
  input[type="submit"],
  input[type="reset"],
  select {
    color: $colorText;
    border-color: $colorText;
  }
}
.fg-foreground {
  color: $colorForeground;
  button, .button,
  input[type="button"],
  input[type="submit"],
  input[type="reset"],
  select {
    color: $colorForeground;
    border-color: $colorForeground;
  }
}
.fg-alternate {
  color: $colorAlternate;
  button, .button,
  input[type="button"],
  input[type="submit"],
  input[type="reset"],
  select {
    color: $colorAlternate;
    border-color: $colorAlternate;
  }
}
.fg-background {
  color: $colorBackground;
  button, .button,
  input[type="button"],
  input[type="submit"],
  input[type="reset"],
  select {
    color: $colorBackground;
    border-color: $colorBackground;
  }
}
.fg-highlight {
  color: $colorHighlight;
  button, .button,
  input[type="button"],
  input[type="submit"],
  input[type="reset"],
  select {
    color: $colorHighlight;
    border-color: $colorHighlight;
  }
}

2 个答案:

答案 0 :(得分:1)

您可以使用@each directive

@each $name, $color in (text: $colorText, foreground: $colorForeground ...) {
  .fg-#{$name} {
    color: $color;
    button, .button,
    input[type="button"],
    input[type="submit"],
    input[type="reset"],
    select {
      color: $color;
      border-color: $color;
    }
  }
}

答案 1 :(得分:0)

我把它浓缩成了一个混音:

@mixin fg($name, $color) {
  .fg-#{$name} {
    color: $color;
    button, .button,
    input[type="button"],
    input[type="submit"],
    input[type="reset"],
    select {
      color: $color;
      border-color: $color;
    }
  }
}
@include fg(brand, $colorBrand);
@include fg(foreground, $colorForeground);
@include fg(background, $colorBackground);
@include fg(text, $colorText);
@include fg(alternate, $colorAlternate);
@include fg(highlight, $colorHighlight);
相关问题