0

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 */
  • possible duplicate of [Dynamic Sass Variables](http://stackoverflow.com/questions/14552529/dynamic-sass-variables) – cimmanon Nov 13 '13 at 13:13

2 Answers2

2

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

Martin Turjak
  • 20,896
  • 5
  • 56
  • 76
  • This was really useful...thanks for introducing SASS maps to me! Worth noting that if you're using libsass, this feature isn't implemented. There is a workaround - [sass-list-maps](https://github.com/lunelson/sass-list-maps). [This article](http://benfrain.com/libsass-lightning-fast-sass-compiler-ready-prime-time/) gave some tips for converting SASS map syntax to something that'll work for sass-list-maps. – Brendan Jun 10 '14 at 20:30
0

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*/ }
Community
  • 1
  • 1
Fendy Kusuma
  • 672
  • 7
  • 16