如何在 SCSS 颜色函数中控制 HSLA Alpha 通道?

问题描述 投票:0回答:2

下面是我正在尝试做的事情的一个例子。我确信有更好的方法可以做到这一点。基本上我希望函数能够通过颜色变量中 hsla 颜色的 alpha 通道,这样我就不必为每种颜色设置多个颜色变量。

我希望能够像这样调用该函数:

.item {background-color: color(blue, dark, .5);}

这是我到目前为止所拥有的:

$base-blue:    hsla(200,100%,50%,1);
$base-blue-50: hsla(200,100%,50%,.5);

$palette: (
    blue: (
        base:  $base-blue,
        light: lighten($base-blue, 10%),
        dark:  darken($base-blue, 10%)
    ),
     blue-50: (
        base:  $base-blue-50,
        light: lighten($base-blue-50, 10%),
        dark:  darken($base-blue-50, 10%)
    )
);

@function color($color, $tone: 'base') {
    @return map-get(map-get($palette, $color), $tone);
}

基本上,如果不需要的话,我不想创建

$base-blue-50
变量。

感谢您的帮助:)

html css sass colors
2个回答
1
投票

如果您使用

$base-blue
而不是
hsl
定义
hsla
,则可以在
color()
函数中动态调整其 alpha 值。

$base-blue: hsl(200, 100%, 50%);

$palette: (
    blue: (
        base:  $base-blue,
        light: lighten($base-blue, 10%),
        dark:  darken($base-blue, 10%)
    )
);

@function color($color, $tone: 'base', $a: 1) {
    $rgb: map-get(map-get($palette, $color), $tone);
    @return rgba($rgb, $a); // Apply the alpha value
}

.item {
    color: color(blue);            // Output: #00aaff
    color: color(blue, light);     // Output: #33bbff
    color: color(blue, dark);      // Output: #0088cc
    color: color(blue, dark, .5);  // Output: rgba(0, 136, 204, 0.5)
}

0
投票
If you need to return hsla, this option does the job by directly changing the alpha channel
@use 'sass:color';

@function alpha($color-name, $new-alpha: 100) {
  $map: map-merge(map-get($themes, 'light'), $colors);
  $color: map-get($map, $color-name);

  @if $color == null {
    @warn "Color `#{$color-name}` is not defined in theme";
    @return null;
  }

  @return color.change($color, $alpha: calc($new-alpha / 100));
}

//返回hsla

© www.soinside.com 2019 - 2024. All rights reserved.