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

Mary-Kate Olsen
Release: 2024-10-28 05:31:02
Original
176 people have browsed it

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:

<code class="scss">section.accent {
    background: $accent;
}

.foo {
    border: $base;
}

.bar {
    color: $flat;
}</code>
Copy after login

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

<code class="scss">html {
  &amp;.sunrise {
    $accent: #37CCBD;
    $base: #3E4653;
    $flat: #eceef1;

    @import "theme";
  }

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

    @import "theme";
 }
}</code>
Copy after login

Using Mixins

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>
Copy after login

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

<code class="scss">html {
  &amp;.sunrise {
    $accent: #37CCBD;
    $base: #3E4653;
    $flat: #eceef1;

    @include theme($accent, $base, $flat);
  }

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

    @include theme($accent, $base, $flat);
 }
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!