Home >Web Front-end >CSS Tutorial >How can I dynamically set Sass color variables based on HTML element classes?
Question: Can I dynamically set Sass color variables based on classes applied to an HTML element?
Answer: Yes, you can achieve this through the use of Sass includes or mixins.
In a separate file (_theme.scss), define the styles using your Sass variables:
<code class="scss">section.accent { background: $accent; } .foo { border: $base; } .bar { color: $flat; }</code>
In your main Sass file (main.scss), import the include based on the class on the HTML element:
<code class="scss">html { &.sunrise { $accent: #37CCBD; $base: #3E4653; $flat: #eceef1; @import "theme"; } &.moonlight { $accent: #18c; $base: #2a2a2a; $flat: #f0f0f0; @import "theme"; } }</code>
Alternatively, you can create a mixin that takes the colors as arguments:
<code class="scss">@mixin theme($accent, $base, $flat) { // Define styles using the passed variables }</code>
In your main Sass file, invoke the mixin with the appropriate colors:
<code class="scss">html { &.sunrise { $accent: #37CCBD; $base: #3E4653; $flat: #eceef1; @include theme($accent, $base, $flat); } &.moonlight { $accent: #18c; $base: #2a2a2a; $flat: #f0f0f0; @include theme($accent, $base, $flat); } }</code>
This approach allows you to apply different themes to HTML elements dynamically based on their classes.
The above is the detailed content of How can I dynamically set Sass color variables based on HTML element classes?. For more information, please follow other related articles on the PHP Chinese website!