How to mask an image in HTML/CSS

Until browsers all agree on a technique for masking an image in HTML (like –web-kit-mask-image), I’ve got another option: using SVG.

image

I’m creating a single page application to help sell some electronics and other goodies I’ve collected over the years. Rather than the traditional rectangular display of photos, I wanted to try something different. I wanted the photos to be round. However, I didn’t want to create a bunch of round images.

Enter SVG:

<svg width="220" height="220">
<mask id="m1"><ellipse cx="110" cy="110" rx="98" ry="98" style="fill:white;stroke-width:0;fill-opacity: 1.0"></ellipse></mask>
<g>
<ellipse cx="110" cy="110" rx="100" ry="100" style="stroke-width:10;stroke:#222"></ellipse>
<image href="img/sales/lenovo/IMG_0468.jpg" x="-25%" y="-25%" height="150%" width="150%" style="mask: url(#m1)"></image></g></svg>

The original images aren’t square, so I tweaked the size and position of each so that it would completely fill the ellipse (150% and -25% for size and location).  As a fall back, I’m going to add the CSS property and value “display:none” to a standard HTML img element that will be optionally displayed if the browser can’t do SVG (like IE8 and lower for example). I don’t want to lose a potential sale to images not showing up! I’ll use modernizr for SVG detection.

And although the code above doesn’t demonstrate the technique, you can use CSS to decorate the SVG. Check this demo out that I created:

image

image

image