Julien Melissas

Code

maybe-rgba() sass function

Posted on .

maybe-rgba() sass function

Introduction

Earlier today I found myself in a funny situation. I have a sass mixin than adds a screen to divs which expects 2 arguments: $color and $opacity. From there, it takes those values and adds the appropriate code. Only problem, is I’m using my new customizer library (coming soon to a GitHub near you, I promise) which allows for color controls to support rgba and normal colors. But I needed a proper rgba color regardless…

What was happening:

When I passed an rgba color to my screen($color, $opacity) mixin, the $opacity was being overwritten because it was doing this essentially when I called it like this: @include screen($color, 1);:

background-color: rgba(rgba(...), 1);

It was spitting out a color with 1 as the opacity regardless. I want the function to work with both rgba and #whatever values. So here goes.

 

Sass Functions are Easy

Seriously. It’s this easy:

@function function-name($variable) {
    @return $value;
}

 

maybe-rgba()

So this is what I came up with, and it’s working great:

/**
* Makes rgba() values only if the existing color isn't already rgba()
*/
@function maybe-rgba($color, $opacity: 0.5) {
    @if (alpha($color)) {
        @return $color;
    } @else {
        @return rgba($color, $opacity);
    }
}

Let’s break this down. You pass a color and a (backup) opacity into this function. I set a default of 0.5. If the color already has an alpha value (using Sass’ native alpha function), just return the color. If not, take the color and return it but with the desired opacity.

 

Why “maybe-“?

Naming things is hard.

 

I actually like to use “maybe-” when I’m unsure about what I’m passing into a function. For me it discourages the use of a function that’s not sure what it needs passed into it. If I can avoid it, it’s great. If I can’t, at least I know that this function is unsure about what is being passed into it and that it will help to clean things up for me in it’s output.

 

Am I an idiot? Let me know in the comments below 😉

Julien Melissas

Julien Melissas

https://www.julienmelissas.com

I'm a Web Developer, Foodie, and Music Lover/Maker living in Asheville, NC. I make things on the web at Craftpeak & JM Labs.

Navigation