Set a variable in Sass depending on the selector

前端 未结 8 1128
失恋的感觉
失恋的感觉 2020-12-10 10:20

I’ve got a website that’s using a few different ‘main’ colors. The general HTML layout stays the same, only the colors change depending on the content.

I was wonderi

8条回答
  •  没有蜡笔的小新
    2020-12-10 10:59

    as sass documentation explain nicely (https://sass-lang.com/documentation/variables):

    • Sass variables are all compiled away by Sass. CSS variables are included in the CSS output.

    • CSS variables can have different values for different elements, but Sass variables only have one value at a time.

    • Sass variables are imperative, which means if you use a variable and then change its value, the earlier use will stay the same. CSS variables are declarative, which means if you change the value, it’ll affect both earlier uses and later uses.

    We may take advantage of that using a combination of sass and css variables to achieve what you want:

    //theme colors
    $red-cosmo: #e01019;
    $green-cosmo: #00c398;
    $primary-color: var(--primary-color);
    body{
      --primary-color: #{$red-cosmo};
    }
    body.univers-ride{
      --primary-color: #{$green-cosmo};
    }
    

    So when I call my sass variable $primary-color, it will print as my css variable "var(--primary-color)" that will expand as $green-cosmo only if my body has the "univers-ride" class else it will be $red-cosmo the default color.

提交回复
热议问题