Web Tech

Use an Illustrator vector shape as a mask in HTML

There's a boat-load of articles showing different ways to do this but most are outdated and overly complicated.  Here's the easiest most straightforward way; it doesn't require any javascript, it's supported by modern browsers, and gracefully degrades for other devices that don't support it by just showing the image.

Make a vector mask in Illustrator

  1. Create the shape you want
  2. Put the artboard tightly around it
  3. Ungroup everything (hit command+shift+g a few times)
  4. Save for the web as an SVG
a simple vector shape in illustrator - in this example it's the Condensed icon


The HTML and CSS

The HTML couldn't be more simple, you just put any old image into your document and add a class to it so you can target it.

For example here's an image of a nice place to visit:

<img src="https://i.postimg.cc/5Ns1NG6s/palm-tree-wallpapers-27997-4355712.jpg" class="mask" />

looks like this:

CSS

This CSS below is all you need, you'll need to change the path to point to the SVG you saved earlier.

/*--- Masks ---*/

.mask {

   mask: url(./images/mask_01.svg) no-repeat;

   -webkit-mask: url(./images/mask_01.svg) no-repeat;

   -o-mask: url(./images/mask_01.svg) no-repeat;

   -ms-mask: url(./images/mask_01.svg) no-repeat;

}

Or if you are running auto-prefixer like we are in this codepen example below you can just add mask: and not worry about the browser prefixes: