Master.Deep
Master.Deep

Reputation: 812

Change all variable value based on body class

I am working on theme based localisation. For that I am getting class on body tag for each localisation. I need to change all variables value based on that class For more Understanding

$a: #000;
$b= Arial;

if body has class Australia then
$a: #ff0000;
$b: 'Roboto';

Please no js code only by scss

Upvotes: 2

Views: 2684

Answers (2)

Jakob E
Jakob E

Reputation: 4926

Using @import and !default variables

// –––––––––––––––––––––––––––––––––––––– 
// _style.scss 
// underscore added to prevent compilation 
// ––––––––––––––––––––––––––––––––––––––

$color      : red   !default;
$font-family: Arial !default; 

.foo { color: $color; }
.bar { font-family: $font-family; }



// ––––––––––––––––––––––––––––––––––––––
// style.scss (compile file) 
// ––––––––––––––––––––––––––––––––––––––
// redefine variables
$color: blue;
$font-family: Roboto;

// add wrapper if needed (will be added to all selectors)
.australia {
    @import '_style.scss';
}

Upvotes: 3

Jakob E
Jakob E

Reputation: 4926

The following example uses a map to define different theme values. The mixin will wrap each selector in a class (the map key) and create global variables to be used inside each selector.

$theme-map:(
  '.australia': (color: blue, font-family: Roboto),
  '.denmark'  : (color: red,  font-family: Arial)    
);


@mixin theme {
  @each $class, $map in $theme-map {
    #{$class} & { 
      $color:       map-get($map, color)       !global;
      $font-family: map-get($map, font-family) !global;
      @content;
    }
  }
}



.foo {
  @include theme {
    color: $color;
    font-family: $font-family;
  }
}


.bar{
  @include theme {
    background-color: $color;
  }
}

Output:

.australia .foo {
  color: blue;
  font-family: Roboto;
}
.denmark .foo {
  color: red;
  font-family: Arial;
}

.australia .bar {
  background-color: blue;
}
.denmark .bar {
  background-color: red;
}

PS. in the near future CSS variables will ease this type of work using variable inheritance.

.australia {
   --color: red;
   --font-family : Arial;
}

.denmark {
   --color: blue;
   --font-family : Roboto;
}



.foo {
   color: var(--color);
   font-family: var(--font-family);
}

.bar {
   backgound-color: var(--color);
}

Upvotes: 0

Related Questions