jfhr / ngb-theme-switcher-example

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

Get theme variables in to component styles #1

Closed ozcancelik closed 3 years ago

ozcancelik commented 3 years ago

Hello.

Thank you for your work. I also want to change the styles of the components in my project, but I want it to be with variables from the based on theme. How can I achieve this. Any ideas?

Thank you.

jfhr commented 3 years ago

Hi, if I'm understanding correctly, you want to change the styles of specific components based on the selected theme? You could define a CSS class for your component, then define different styles for that class in each theme. Then, when the user selects a new theme, the styles from that theme will be applied to the component.

E.g. in your component.html

<div class="my-class">...</div>

In your theme files, e.g. theme1.scss:

.my-class {
    /* your styles here */
}

Putting those rules in your global theme Stylesheets means they won't be component-scoped, so I'd recommend defining new classes for each component to prevent conflicts.

Hope that helps!

ozcancelik commented 3 years ago

You re saying putting that class/css inside just one theme css.(i.e. dark.scss) It's easy solution. But I don't want to use single css. My project will be getting bigger. So there is no way to use component base css with variables. At least in multiple themes.

Thank you.

jfhr commented 3 years ago

I guess as an alternative you could use CSS variables in your component Stylesheet, and set a different value for the CSS variables in each theme Stylesheet. E.g. in dark.css:

* {
  --bg-color: black;
}

And in light.css:

* {
  --bg-color: white;
}

Then in your component Stylesheet, you would use those CSS variables:

.some-class {
  background-color: var(--bg-color);
}
ozcancelik commented 3 years ago

Very good idea. I thought I should import for plain css variables to component css as well. But since there is no need to import the components, the variables of whatever theme comes and works fine. Thank you so much.

Also, I call mixin, functions, variables from bootstrap into components.

@import "~/node_modules/bootstrap/scss/functions";
@import "~/node_modules/bootstrap/scss/variables";
@import "~/node_modules/bootstrap/scss/mixins";

I can also use variables other than color (for example: @include media-breakpoint-down(lg) {..}) in component scss. When I need to add color, I use the variables I assigned as --primary.

To summarize for those who have a similar problem, it is necessary to assign extra css variables and use them in order to use colors in different themes in the component. At least for Bootstrap 5.