Home > Software engineering >  How to make sass button modifier class more generic
How to make sass button modifier class more generic

Time:12-07

I'd like to make a btn--outline modifier class that would invert the button. I can't possibly come with a solution that would make it work for any given color without manually doing it.

The wanted solution is that the third button should have lightgreen text and border. If btn--outline was added to the forth one, it should have salmon text and border in that case.

html

    <button class="btn">First button</button>
    <button class="btn btn--secondary">Second button</button>
    <button class="btn btn--secondary btn--outline">Third button</button>
    <button class="btn btn--tertiary">Fourth button</button>

scss

* {
  box-sizing: inherit;
}

body {
  font-size: 62.5%;
  box-sizing: border-box;
}

.btn {
  border: none;
  padding: 1rem 2rem;
  margin: 1rem;
  border-radius: 9px;

  font-size: 1.2rem;
  line-height: 1.2rem;

  color: #333;
  background-color: lightblue;

  &--secondary {
    background-color: lightgreen;
  }

  &--tertiary {
    background-color: salmon;
  }

  &--outline {
    color: currentColor; // How to get color that button had on the background-color property?
    border: 1px solid currentColor;
    background-color: transparent;
  }
}

CodePudding user response:

You could try using a SCSS map:

$variants: (
  primary: lightblue,
  secondary: lightgreen,
  tertiary: salmon
);

.btn {
  border: none;
  padding: 1rem 2rem;
  margin: 1rem;
  border-radius: 9px;

  font-size: 1.2rem;
  line-height: 1.2rem;

  color: #333;
  background-color: lightblue;

  @each $variant, $color in $variants {
    &--#{$variant} {
      background-color: $color;
    }
    &--#{$variant}.btn--outline {
      background-color: transparent;
      color: $color;
      border: 1px solid $color;
    }
  }
}

CodePudding user response:

Thank you @adrianmanduc

With help from your solution in the end I've come up with this:

Codepen.io solution

$primary-color: lightblue;
$secondary-color: lightgreen;
$tertiary-color: salmon;

@mixin invert-button($col) {
  background-color: transparent;
  color: $col;
  border: 1px solid $col;
}

$button-variants: (
  secondary: $secondary-color,
  tertiary: $tertiary-color
);

.btn {
  border: none;
  padding: 1rem 2rem;
  margin: 1rem;
  border-radius: 9px;

  font-size: 1.2rem;
  line-height: 1.2rem;

  color: white;
  background-color: $primary-color;

  &--outline {
    @include invert-button($primary-color);
  }

  @each $variant, $color in $button-variants {
    &--#{$variant} {
      background-color: $color;
    }
    &--#{$variant}.btn--outline {
      @include invert-button($color);
    }
  }
}
  • Related