Home  >  Article  >  Web Front-end  >  How to Dynamically Style HTML Elements with Sass Variables: Includes vs Mixins?

How to Dynamically Style HTML Elements with Sass Variables: Includes vs Mixins?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 16:58:25423browse

How to Dynamically Style HTML Elements with Sass Variables: Includes vs Mixins?

Styling HTML Elements Dynamically with Sass Variables

Scenario:

You want to assign dynamic color variables to HTML elements based on their classes.

Solution:

Sass provides two methods to achieve this:

1. Using Includes

Create a separate "_theme.scss" file with the following code:

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

.foo {
  border: $base;
}

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

In your main Sass file, import the "_theme.scss" file within the "&" selector blocks:

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

    @import "theme";
  }

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

    @import "theme";
  }
}</code>

2. Using Mixins

Define a mixin "_theme" that takes three color arguments:

<code class="scss">@mixin theme($accent, $base, $flat) {
  // Sass code to style the elements
}</code>

Then, apply the mixin to different class selectors within "&" blocks:

<code class="scss">html {
  &.sunrise {
    @include theme(#37CCBD, #3E4653, #eceef1);
  }

  &.moonlight {
    @include theme(#18c, #2a2a2a, #f0f0f0);
  }
}</code>

Both methods allow you to dynamically change the colors of elements based on the classes they possess.

The above is the detailed content of How to Dynamically Style HTML Elements with Sass Variables: Includes vs Mixins?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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