0
votes

Trying to get Sass to change my $brand_clr color variable depending on the page (via class on the body element). For example, home background will be blue, about us will be green, contact page will be orange, etc... Want to do this without declaring a bunch of color variables. The variable will change button colors, background color, link colors, etc...

$brand_clr: blue;

body.home { background: $brand_clr; } /* This will be blue */
body.about { background: $brand_clr; } /* This will be orange */
body.contact { background: $brand_clr; } /* This will be yellow */
2
possible duplicate of Dynamic Sass Variablescimmanon

2 Answers

2
votes

As of Sass v3.3 you could try out maps - sounds like this could be a very nice case for using them. They allow you to store keys and their values in one map variable:

$brand_clr: (home: blue, about: orange, contact: yellow);

Then you can access a single value by its key using the get-map() function:

background: map-get($brand_clr, about);

Then you can loop through the map and avoid a lot of hardcoding:

@each $brand, $clr in $brand_clr {
  body.#{$brand} {
    background: $clr;
  }
  // and other selectors that change with the brand
}

Or even better - design a mixin that you can include in any rule set:

$color: red !default; // some default color - will be overwritten by brand color
@mixin branding {
  @each $brand, $clr in $brand_clr {
    &.#{$brand} {
      $color: $clr;
      @content;
    }
  }
}

body {
  @include branding {
    background: $color;
  }
}

DEMO

If you are on Sass <=3.2 you can achieve a similar thing with lists instead of maps:

$brand_clr: (home, blue), (about, orange), (contact, yellow);

and in the mixin you can access the individual values by it's index using nth():

$color: null;
@mixin branding {
  @each $brand in $brand_clr {
    &.#{nth($brand,1)} {
      $color: nth($brand,2);
      @content;
    }
  }
}

DEMO

0
votes

You may lookup for this answer. You just need to adjust your class like those..

body.home.color-1 { /*Background Color 1*/ }
body.home.color-2 { /*Background Color 2*/ }
body.home.color-3 { /*Background Color 3*/ }