"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I dynamically set Sass color variables based on HTML element classes?

How can I dynamically set Sass color variables based on HTML element classes?

Published on 2024-11-03
Browse:619

How can I dynamically set Sass color variables based on HTML element classes?

Configuring Dynamic Sass 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.

Using Includes

In a separate file (_theme.scss), define the styles using your Sass variables:

section.accent {
    background: $accent;
}

.foo {
    border: $base;
}

.bar {
    color: $flat;
}

In your main Sass file (main.scss), import the include based on the class on the HTML element:

html {
  &.sunrise {
    $accent: #37CCBD;
    $base: #3E4653;
    $flat: #eceef1;

    @import "theme";
  }

  &.moonlight {
    $accent: #18c;
    $base: #2a2a2a;
    $flat: #f0f0f0;

    @import "theme";
 }
}

Using Mixins

Alternatively, you can create a mixin that takes the colors as arguments:

@mixin theme($accent, $base, $flat) {
    // Define styles using the passed variables
}

In your main Sass file, invoke the mixin with the appropriate colors:

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);
 }
}

This approach allows you to apply different themes to HTML elements dynamically based on their classes.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3