Why does a CSS linear-gradient from color1 to color2 render exactly the same as a linear-gradient from color1 to transparent on a color2 background?

Viewed 132

A linear gradient from red to blue can be created with:

background: linear-gradient(
              rgb(255,0,0),
              rgb(0,0,255))

To create this:

If you instead faded red to transparent and placed that on a blue background with:

background: linear-gradient(
              rgb(255,0,0), 
              rgb(255,0,0,0)),
            rgb(0,0,255);

The result is exactly the same:

In the first example, the center of the image would have RGB values (127.5, 0, 127.5), by linear interpolation.

In the second example, the center of the image is a combination of a partially transparent red (127.5, 0, 0, 0.5) and a solid blue (0, 0, 255). How are these combined to create the same (127.5, 0, 127.5) result as in the first example?

1 Answers

You have a mistake in your conclusion. The interpolation of the second gradient will give a center coloration of (255, 0, 0, 0.5) and not (127.5, 0, 0, 0.5)

and (255, 0, 0, 0.5) on the top of (0, 0, 255, 1) will give (127.5, 0, 127.5)

    255*0.5 + 0*(1 - 0.5) = 127.5
    0*0.5   + 0*(1 - 0.5) = 0 
    0*0.5   + 255*(1 - 0.5) = 127.5 

More details around the math here: Color of stacked semi-transparent boxes depends on order?

Related