Search code examples
htmlcsscss-filterscss-mask

Blur a single side of an image


How can I blur one side of an image to create a nice transition from the image to a background?

I was able to do it with this little hack:

.wrapper {
    width: 200px;
    height: 250px;
    overflow: hidden;
}
.image-blurred {
    background-image: url('http://lorempixel.com/200/200/city/9');
    width: 200px;
    height: 200px;
    filter: blur(15px);
    position: relative;
}

.frontimage {
    position: absolute;
    top:0px;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
<div class="wrapper">
<div class="image-blurred"></div>
<div class="frontimage"><img src="http://lorempixel.com/200/200/city/9"></div>
</div>

but -webkit-mask-image is not a reliable option.

Is there any other ways to achieve that?


Solution

  • You need to correctly write the mask and it's reliable https://caniuse.com/#feat=css-masks (only IE is not supported which is not a surprise)

    You can also simplify your code like below:

    .frontimage img {
      filter: blur(15px);
    }
    .frontimage {
      position:relative;
      display:inline-block;
      padding-bottom:50px;
      overflow: hidden;
    }
    
    .frontimage::after {
      content:"";
      position:absolute;
      background-image: url('http://lorempixel.com/200/200/city/9');
      top: 0;
      left:0;
      right:0;
      bottom:50px;
      -webkit-mask-image: linear-gradient(to bottom, #fff, transparent);
              mask-image: linear-gradient(to bottom, #fff, transparent);
    }
    <div class="frontimage">
          <img src="http://lorempixel.com/200/200/city/9">
    </div>

    Related question to get a different effect: Mask Image, create rectangle from multiple gradients