Skip to Content

Masking images with CSS and jQuery

Ever wanted to add a pretty frame or porthole effect to images uploaded through a content management system? Just a few lines of jQuery and a custom CSS class can overlay a mask on all marked images:

(function($){
$(document).ready(function($){
  $('.maskable').each(function(){
    var $this = $(this);
    $this.css({
      'background':'url(' + this.src + ') center center no-repeat'
    })
    .attr('src','/path/to/images/mask.png');
  });
});
})(jQuery);

Now, upload a mask image (mask.png in the example above) with a transparent center and layout your images as follows:

<img class="maskable" src="/path/to/images/image.jpg" />

No Javascript? No problem. Without script support, your visitors will still see the square (boring) version of the image you uploaded. The only thing to watch out for are older version of IE that don’t support PNG transparency. Don’t forget to use a plugin like pngFix to help them out!

Update: I’ve wrapped this technique up into a micro-plugin:

$.fn.maskable = function (opts) {
  var options = $.extend({
    maskSrc: '/path/to/mask.png'
  }, opts);

  $(this).each(function () {
    var $img = $(this);
    $img.css('background', 'url(' + $img.attr('src') + ') center center no-repeat').attr('src', options.maskSrc);
  });
}

Once this code is included, subsequent calls to maskable may be made like this:

$('.maskable').maskable({ maskSrc: '/path/to/mask.png' });

A working demonstration is available here




  • Me

    Doesnt work

    • Chris Giddings

      Works fine for me.

  • Martin Michael

    Hello from Germany
    Good Job really good job

    • http://twitter.com/rjzaworski RJ Zaworski

      vielen dank! :^)

  • pama

    Hi,

    Realy thanks for this,work just fine form me.
    I also have a question for you.Is tehe any solution for masking all .div .. I need it for slider masking. Many thanks!!

  • Naahh

    Great! Thank you very much, sir!

  • Nitin Pant

    Doesn’t work for me, copied from Jsfiddle