GeorgeButter
GeorgeButter

Reputation: 2591

Sass - Repeating code, how can I make this more succinct

I am creating helper classes that change the colour to predefined variables. For the most part the code is the same. I will be adding more specific selectors to this how can I make this easier to maintain?

.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;
  }
}

Upvotes: 0

Views: 33

Answers (2)

Johannes Müller
Johannes Müller

Reputation: 5661

You could use an @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;
    }
  }
}

Upvotes: 1

GeorgeButter
GeorgeButter

Reputation: 2591

I have condensed it to a mixin:

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

Upvotes: 0

Related Questions