Change All Variable Value Based on Body Class

Dynamically change a variable based on class name

For sure SCSS provide such function but you can also do it with CSS using CSS variables:

.object h1 {  font-size: 40px;  color: var(--p, blue);}
.object p { font-size: 20px; color: var(--p, blue);}.red { --p:red;}.other-color { --p:rgb(15,185,120);}
<div class="object"><h1>Blue title</h1><p>blue text</p></div><div class="object red"><h1>red title</h1><p>red text</p></div><div class="object other-color"><h1>red title</h1><p>red text</p></div>

Set a variable in Sass depending on the selector

I think a mixin is the answer. (As I wrote, variables won’t work.)

@mixin content($color-default, $color-main) {
background: $color-default;
color: $color-main;
}

body.class-1 {
@include content(#444, #555);
}

body.class-2 {
@include content(#666, #777);
}

That SCSS compiles to this CSS:

body.class-1 {
background: #444444;
color: #555555; }

body.class-2 {
background: #666666;
color: #777777; }

If you wanted to group the color values together in your SCSS file, you could use variables in conjunction with the mixin:

$color-1: #444;
$color-2: #555;
$color-3: #666;
$color-4: #777;

body.class-1 {
@include content($color-1, $color-2);
}

body.class-2 {
@include content($color-3, $color-4);
}

Scss Variable based on class

I personally prefer using a function for that, but you could make it with a mixin too.

Create a Map with properties bind to as many values as themes you have.

Then, define a custom property for fetching this map and return the wanted value.

$theme: (
color: (#000, #FFF),
border: (dashed, solid),
// etc.
);

@function theme($property, $index) {
@return nth(map-get($theme, $property), $index);
}

.light.foo {
color: theme(color, 1);
}

.dark.foo {
color: theme(color, 2);
}

Demo SassMeister



Related Topics



Leave a reply



Submit