Search code examples
csscolorshextransparencyrgba

How to convert rgba to a transparency-adjusted-hex?


I'm wondering how to convert rgba into hex in a way that translates the visible rgba-color (including transparency) into a hex value.

Say I have this:

rgba(0,129,255,.4)

Which is sort of a "light blue"...

I would like to know if there is a way to get the same light blue "visible" color in hex, so I don't want the converted #0081ff but something close to the color visible on screen.

Question:
How to convert rgba to a transparency-adjusted-hex?


Solution

  • It depends on the background to which your transparent color will be applied. But if you know the color of the background (e.g. white), you can calculate the RGB color resulting of the RGBA color applied to the specific background.

    It's just the weighted average between the color and the background, the weight being the alpha channel (from 0 to 1) :

    Color = Color * alpha + Background * (1 - alpha);
    

    For your transparent light blue rgba(0,129,255,.4) against white rgb(255,255,255) :

    Red   =   0 * 0.4 + 255 * 0.6 = 153
    Green = 129 * 0.4 + 255 * 0.6 = 204.6
    Blue  = 255 * 0.4 + 255 * 0.6 = 255
    

    Which gives rgb(153,205,255) or #99CDFF