Some words about transparency

It is now common practice in WEB design to overlay semi-transparent elements over a particular background, and, moreover, to stack a number of semi-transparent elements. When implementing the design it might be desirable to calculate the resulting, or final, color.

To describe transparency, the fourth component, opacity, is added to the color triplet. The fourth value stands for opacity, with 0 means fully transparent and 1 stands for non-transparent element. Instead of rgb() we use rgba() to describe a transparent elements.

Take, for example, red color, rgb(255, 0, 0). Semi-transparent red is rgba(255, 0, 0, 0.5). Think of it as a transparent red film. What we see through the film depends not only on the film's color but also on what is behind it. RGBA(255,0,0, 0.5) on a red background produces pure red color, on the blue background we get something violet. RGBA is not, strictly speaking, a color, it is about changes to the underlying colors.

How are colors actually combined. Colors and transparent layers are not directly summed up. The result is rather a weighted sum with weights of (1-opacity) for background and opacity for the overlay color. E.g opacity 0.8 means: take 20% of the background color and 80% of the overlay color.

        Final = backgroud * (1-opacity) + overlay * opacity
      

Some special cases help to feel how it works. When opacity is zero (fully transparent element), rgba(r,g,b,0), the first three color components make no difference: whatever color the background is, it remains intact. While with opacity 1, we do not see background at all, and the final color is fully defined by the color components of our rgba element.

Another remarkable property is that the order of semi-transparent elements in the stack is siginficant: see below.