Read more

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

Arne Hartherz
September 23, 2016Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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)
Posted by Arne Hartherz to makandra dev (2016-09-23 11:01)