Search code examples
htmlcsssasscolors

How do you control an HSLA alpha channel in a SCSS color function?


Below is an example of what I'm trying to do. I'm sure there's a better way of doing this. Basically I want the function to pass through the alpha channel of the hsla color in the color variable so I don't have to have multiple color variables for each color.

I'd like to be able to call the function like this:

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

Here's what I have so far:

$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);
}

Basically I don't want to have to create the $base-blue-50 variable if I don't have to.

Thanks for your help with this :)


Solution

  • If you define $base-blue using hsl instead of hsla, you can adjust its alpha value dynamically within your color() function.

    $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)
    }