Search code examples
cssimagereflectioneffectmirror

How to simply create an image reflection effect in JavaScript/CSS?


I have spent some time to look up how to best create a dynamic image reflection effect.

Options I found were:

  • non-standard browser tags such as -webkit-reflect,

  • adding libraries from <2012 that all have outdated dependencies and fail when combining with e.g. up to date JQuery 3, or

  • dropping the idea of dynamic image reflections and relying on GIMP/Photoshop.

  • Also most existing solutions fail on non plain background, i.e. textures.

The drawbacks of the above lie at hand. Unfortunately I do not have a web blog where to post what I came up with, yet I think it would be worth sharing (see self-answer below).


Solution

    1. Add an image to your HTML:
    <img class="reflect" src="some/image.png" />
    
    1. Add the following CSS rules:
    img.reflect {
      width: calc(100% - 20px); /* not sure how else to allow for margin */
      margin-left: 10px;
    }
    
    img.reflection {
      position: absolute;
      opacity: 0.4;
      margin-top: 4px;
      width: calc(100% - 20px);
      -webkit-mask-image: -webkit-linear-gradient(transparent 75%, black 100%);
      mask-image: linear-gradient(transparent 75%, black 100%);
      -webkit-transform: translateX(calc(-100% - 10px)) translateY(100%) scaleY(-1) ;
      transform: translateX(calc(-100% - 10px)) translateY(100%) scaleY(-1);
    }
    

    If you don't want to rely on any JavaScript you could now simply add the reflection by inserting the reflection tag right after the image tag from (1):

    <img class="reflection" src="some/image.png" />
    

    Otherwise

    1. For example, extend JQuery with the following function:
    $.fn.reflect = function() {
        var reflection = this.clone();
        this.after(reflection);
        reflection.addClass("reflection");
    };
    
    1. Then reflect the image:
    $(".reflect").reflect();