3

Say I have a module button like this (button.scss):

.m-button {
    width: 125px;
    height: 35px;
    color: white;
    display: inline-block;
}

And a colors file like this which defines colors (colors.scss):

$light-grey: #EFEFEF;
$dark-grey: #4E4E4E;
$less-dark-grey: #5F5F5F;

I want to be able to put these buttons throughout my site, and easily choose a background color for the button by assigning it the correct class like this:

<div class="m-button background-light-grey">Click Me </div>

But I'd like to avoid having to write all the background-color definitions. Is it possible in SASS using mixins or functions to do basically look at all my colors and make a background-color class for each one which sets the background-color style appropriately?

asolberg
  • 6,638
  • 9
  • 33
  • 46
  • You'll have to make an individual class for each button (primary-button, danger-button, secondary-button,etc.), extending the button class and setting the background color to one of your defined colors. http://css-tricks.com/the-extend-concept/ – Jeffpowrs May 27 '14 at 19:38
  • Looks like there's no direct way of doing that, except using a list, but you still have to write each color again. See http://stackoverflow.com/questions/7209031/is-it-possible-to-use-variable-names-dynamically-in-sass-each-loop. – Alexandrin Rus May 27 '14 at 19:44
  • Ack, didn't realize I got the gold badge when I marked this one. This question is better: http://stackoverflow.com/questions/16585390/using-sass-for-loop-to-define-variable-color – cimmanon May 27 '14 at 20:03

1 Answers1

2

Check the following solution:

$colors: (
  light-grey: #EFEFEF,
  dark-grey: #4E4E4E,
  less-dark-grey: #5F5F5F
);

@mixin button-colors {
  @each $name, $color in $colors {
    .background-#{$name} {
      background: $color;  
    }
  }
}

@include button-colors;

.m-button {
  width: 125px;
  height: 35px;
  color: white;
  display: inline-block;
}

OUTPUT

.background-light-grey {
  background: #efefef;
}

.background-dark-grey {
  background: #4e4e4e;
}

.background-less-dark-grey {
  background: #5f5f5f;
}

.m-button {
  width: 125px;
  height: 35px;
  color: white;
  display: inline-block;
}

An example: http://sassmeister.com/gist/2f6822da159348908041

Vangel Tzo
  • 8,885
  • 3
  • 26
  • 32
  • Yeah, I think that's the only way you can achieve something similar, the only problem is that the initial variables definition must remain intact if they are used in other parts of the sass files, so you would still end up repeating each color, once defining the variable and once in the list for the @each loop. – Alexandrin Rus May 27 '14 at 19:53
  • @AlexandrinRus Yes I can't think of a way without a list.. but I think it's a clean way even if you have to repeat the color variables. – Vangel Tzo May 27 '14 at 20:06