Search code examples
cssimagetransparency

Fade two images together in CSS


Say I have these two images:

How do I combine them like this, where one fades gradually into the other, using just CSS?

I need to do this using CSS because the images are user-supplied.

I've tried using CSS gradients, multiple background images, and blending modes, but wasn't able to achieve what I wanted. Also, wasn't able to find what I needed by googling.


Solution

  • Here's a solution using the mask-image property.

    Scale the browser window to see the images cross fade.

    #Wrap {
      position: relative;
      height: 300px;
      width: 100%;
    }
    
    #Left,
    #Right {
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
    }
    
    #Left {
      left: 0;
      background: url('https://i.sstatic.net/kqa1P.jpg') top left no-repeat;
      -webkit-mask-image: -webkit-linear-gradient(right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1));
      background-size: contain;
    }
    
    #Right {
      right: 0;
      background: url('https://i.sstatic.net/UvGLY.jpg') top right no-repeat;
      -webkit-mask-image: -webkit-linear-gradient(right, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
      background-size: contain;
    }
    <div id="Wrap">
      <div id="Left"></div>
      <div id="Right"></div>
    </div>