jfhr / ngb-theme-switcher-example

Angular + Bootstrap theme switcher example
Creative Commons Zero v1.0 Universal
8 stars 5 forks source link

Not able to update variable in custom css #7

Open rohitspawar2911 opened 1 year ago

rohitspawar2911 commented 1 year ago

Hello I have used this theme switcher and it's working. But the issue is when I have to write a custom CSS class and want to use Bootstrap variable its not reflecting. ex: In custom.scss body{ background: $primary; }

dark.scss $primary: #000000;

light.scss $primary: #ff0000;

CSS after compilation: For Both Theme: custom.css body{ background:#007bff; // Bootstrap default Variable }

If Dark Theme bootstrap.css body{ background:#00000; }

If light theme: body{ background:#ff0000; }

Can you please help me to solve this issue? Thanks

jfhr commented 1 year ago

Yea, this is because of how angular creates stylesheets. The code in custom.scss is compiled once, using the variable values that are set for that file at build time. In your case, custom.scss uses the bootstrap default variables.

One workaround is to use CSS variables instead of bootstrap variables. CSS variables can change at runtime when you select a different theme. I've created a pull request #8 to demonstrate how it could work, but the short version is:

In custom.scss:

body{
  // use the CSS variable --primary
  background: var(--primary);
}

In dark.scss:

$primary: #000000;
// Create a CSS variable --primary with the same value as the bootstrap variable $primary
* {
  --primary: #{$primary};
}

In light.scss:

$primary: #ff0000;
// Create a CSS variable --primary with the same value as the bootstrap variable $primary
* {
  --primary: #{$primary};
}

CSS variables are supported in all modern browsers.

Hope this helps!