Home > Web Front-end > CSS Tutorial > 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
Release: 2024-10-30 16:58:25
Original
436 people have browsed it

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

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

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

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

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!

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