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

Was this helpful? Share it on Twitter or subscribe for (very) occasional updates.