Sass: How to convert an RGBA color to its RGB look-alike

Updated . Posted . Visible to the public.

Say you have an RGBA color that you need as a non-transparent color because of reasons.

Basically, this is possible. Just understand that you will convert your RGBA color for exactly one base background color as you are giving up transparency.
Most likely, your background is white, so you'll use #fff as that for examples below.

Simple approach

When your know the RGBA color's base RGB color (e.g. your brand color that you RGBA'd for some hover effect), you can simply use the mix function instead of rgba.

Before:

background-color: rgba($my-color, .25)

After:

background-color: mix($my-color, #fff, 25%)

Here we mix our color with our known background (we assume white), giving 25% to our color. That's just like it would appear on white background with a .25 alpha channel.

Advanced: Sass function that does all the magic for you

If you don't know the base RGB color, you can extract it using the red, green, and blue Sass functions. The following is basically the solution above, but also computes the base color and transparency value for you.

@function rgba-to-rgb($rgba, $background: #fff)
  @return mix(rgb(red($rgba), green($rgba), blue($rgba)), $background, alpha($rgba) * 100%)

Now use it like any other Sass function.

background-color: rgba-to-rgb($my-transparent-color)

Or, for a different background:

background-color: rgba-to-rgb($my-transparent-color, #ccc)
Arne Hartherz
Last edit
Arne Hartherz
Keywords
opacity, scss
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2016-09-23 09:01)