← Back home

Using SVG clipPath

One neat thing you can do with SVG, besides creating your own image filters, is creating a clipping path (or mask) that can be used to alter the shape of your images and the boundaries of links, the latter being what most excites me because you can now easily create links that are whatever shape you'd like instead of being restricted to a box. I've created a quick demo demonstrating the use of a clipPath on images. These SVG images are wrapped with a link element, which you'll notice its boundaries form around the clipPath and not the image's original boundary box, changing the link's boundary box to a hexagon. Go ahead and mouseover the images to see what I'm talking about.

View demo.

The basic code looks like this. You first want to create a clipPath and assign an ID to it, which you'll use on your images as a reference. Whatever you place within the clipPath will be used as the silhouette (the part that will get displayed). In my instance, I created a hexagon.

You might be wondering why I'm creating the clipPath and wrapping it within a grouping element rather than a defs element. This addresses a bug that I've noticed within Safari, and seems to be the only way to get it to work. Hopefully this gets fixed soon.

After creating our clipPath, we can then apply it to our images. Here's an example of that:

One thing to note, in SVG we need to use the namespaced href attribute, and include the namespace definition in our SVG opening tag, like so:

Browser Support

Inline SVG and clipPaths are supported in the latest versions of Safari and IE, Chrome 17+, and Firefox 8+. You can use Modernizr to check for support and provide a fallback to a non-clipPath version.

View demo.