scss SASS颜色函数和CSS变量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scss SASS颜色函数和CSS变量相关的知识,希望对你有一定的参考价值。

// https://codyhouse.co/blog/post/how-to-combine-sass-color-functions-and-css-variables
.component {
  background-color: alpha(var(--color-primary), 0.2);
}

// return css color variable with different opacity value
@function alpha($color, $opacity){
  $color: str-replace($color, 'var(');
  $color: str-replace($color, ')');
  $color-h: var(#{$color+'-h'});
  $color-s: var(#{$color+'-s'});
  $color-l: var(#{$color+'-l'});
  @return hsla($color-h, $color-s, $color-l, $opacity);
}

// replace substring with another string
// credits: https://css-tricks.com/snippets/sass/str-replace-function/
@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}

@mixin defineColorHSL($color, $hue, $saturation, $lightness){
  #{$color}: unquote("hsl(#{$hue}, #{$saturation}, #{$lightness})");#{$color}-h: #{$hue};#{$color}-s: #{$saturation};#{$color}-l: #{$lightness};
}

:root, [data-theme="default"] {
  @include defineColorHSL(--color-primary, 220, 89%, 56%);
  @include defineColorHSL(--color-accent, 355, 90%, 61%);
  @include defineColorHSL(--color-black, 240, 8%, 12%);
  @include defineColorHSL(--color-white, 0, 0%, 100%);
  // color contrasts
  @include defineColorHSL(--color-bg, 0, 0%, 100%);
  @include defineColorHSL(--color-contrast-lower, 0, 0%, 95%);
  @include defineColorHSL(--color-contrast-low, 240, 1%, 83%);
  @include defineColorHSL(--color-contrast-medium, 240, 1%, 48%);
  @include defineColorHSL(--color-contrast-high, 240, 4%, 20%);
  @include defineColorHSL(--color-contrast-higher, 240, 8%, 12%);
}

以上是关于scss SASS颜色函数和CSS变量的主要内容,如果未能解决你的问题,请参考以下文章

SCSS / SASS:如何在每个循环中创建变量

8.9随笔

Scss 基本使用(变量嵌套)

每日分享

如何使用类似于 SASS 的 darken() 的 CSS 变量创建颜色阴影?

如何使用类似于 SASS 的 darken() 的 CSS 变量创建颜色阴影?