HTML5 and CSS3 Advent 2011

Behind the mask

Using masks to partially reveal content is a pretty common practice in the design world but until now proved to be problematic in front-end development, especially if the masks needed to be dynamic or scalable. Thanks to SVG and a bit of cross-browser hackery we can now do masking in your browser.

Using an SVG mask image

Effect!

Using background-clip: text. Only works on Safari/Chrome!

How does it work?

Applying masks

To make this work in Firefox as well as the webkit browsers, we need our mask as an SVG mask and as an SVG image. Luckily we can combine both into one file. For webkit, we apply the mask by setting -webkit-mask-box-image: url(svgfile.svg#id); (the -webkit-mask-box-image is used so the browser scales our SVG to the full size). For firefox we apply the SVG mask by setting mask: url(svgimage.svg#svgmaskid);.

A thing worth mentioning: you have to convert the coordinates for the mask to percentages (0 to 1) as they can be applied to any size object. Took us quite a while to figure that one out!

Text masking

Another goody (most unfortunately Webkit browsers only) is the background-clip: text property to make backgrounds clip to the text within. It's as simple as setting -webkit-background-clip: text. As it's a background it's hiding behind the actual text, so we have to make the text transparent. The first thing that comes to mind is to set color: transparent, but that would hide the text in browsers without support for -webkit-background-clip too. That's why we're using the -webkit-text-fill-color to set the text's color to transparent.

Show us the source!

Feel free to look around the different source files we used for this example.

Check out our all new HTML & CSS Advent 2012