Dynamic Sass Variables

2020-01-24 16:56发布

Is there any way I can set my color variables depending on what class is on the html element? Or any other way to achieve this same goal?

html {

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

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

}

标签: css sass
3条回答
▲ chillily
2楼-- · 2020-01-24 17:22

Unfortunately, Sass/Scss files need to get compiled into Css files, in order to be supported in your web-browser.

Since Css files don't support variables, you can only set a variables value in the Scss template, because the Sass compiler will replace the var. (in every position, the var. has been used), with the given value.

That means, that it does not help to change the color of the variable, depending on what class is included in the Html file, because the Css file won't contain any variables.

The only way you could do such thing, is by:

  1. reading the Html file to find out what class has been used,
  2. than changing the Scss template variables to the right color value
  3. and compiling the Scss template into an Css file
查看更多
Juvenile、少年°
3楼-- · 2020-01-24 17:34

If you like to use JavaScript, you can do this:

  • You will need an HTML element with an Id and a Class (the one that will decides, what color to use).

    ...

  • Next, you will need to add some JavaSript

    var CurrentColor = document.getElementById("Target").className;

    if (CurrentColor == "sunrise")

    { document.exampleTagg.style.exampleProperty = "#37CCBD"; }

    else if (CurrentColor == "moonlight")

    { document.exampleTagg.style.exampleProperty = "#18c"; }

(the first line will declare a variable, that contains the value of our exampleTagg element (the one with the "Target" id), then the if statement will find out the name of our class (sunrise or moonlight) and last, we will change the background of our exampleTagg to the color we like to)

To use this example for your own purposes, replace the exampleTagg with some real tagg and change the exampleProperty to an valid Css property.

Notice, that you will not need Scss for this job (u can still use it), because JavaScript will access your compiled Css file.

查看更多
孤傲高冷的网名
4楼-- · 2020-01-24 17:42

This is basic theming. You would either want to use a mixin or include to do multiple themes in a single CSS file. This is how you would go about it using includes:

_theme.scss

section.accent {
    background: $accent;
}

.foo {
    border: $base;
}

.bar {
    color: $flat;
}

main.scss

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

    @import "theme";
  }

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

    @import "theme";
 }
}

You could just as easily make a mixin that takes 3 colors as its arguments to use in place of the include:

@mixin theme($accent, $base, $flat) {
    // .. do stuff ..
}
查看更多
登录 后发表回答