Text masking — The standards way

2 min read 0 comments Report broken page

As much as I like .net magazine, I was recently outraged by their “Texturizing Web Type” article. It features a way to apply a texture to text with -webkit-mask-image, presenting it as an experimental CSS property and misleading readers. There are even -moz-, -o- and -ms- prefixes for something that is not present in any specification, and is therefore unlikely to ever be supported by any non-WebKit browser, which further contributes to the misdirection. A while back, I wrote about how detrimental to our work and industry such proprietary features can be.

A common response to such complaints is that they are merely philosophical and who cares if the feature works right now and degrades gracefully. This argument could be valid for some cases, when the style is just a minor, gracefully degrading enhancement and no standards compliant alternative is present (for example, I’ve used ::-webkit-scrollbar styles myself). However, this is not the case here. We have had a standards compliant alternative for this for the past 11 years and it’s called SVG. It can also do much more than masking, if you give it a chance. Here’s an example of texturized text with SVG:

Edit: Thanks to @devongovett’s improvements, the code is now simpler & shorter.

Yes, the syntax might be more unwieldy but it works in a much wider range of browsers: Chrome, Safari, Firefox, IE9, Opera. Also, it’s trivial to make a script that generates the SVG markup from headings and applies the correct measurements for each one. When WebKit fixes this bug, we can even move the pattern to a separate SVG file and reference it from there.

In case you’re wondering about semantics, the <svg> element is considered “flow content” and is therefore allowed in heading elements. Also, even if search engines don’t understand inline SVG, they will just ignore the tags and still see the content inside the <text> element. Based on that, you could even make it degrade gracefully in IE8, as long as you include the HTML5 fix for the <svg> element. Then the CSS rules for the typography will still apply. You’ll just need to conditionally hide the <image>, since IE8 displays a broken image there (a little known fact is that, in HTML, <image> is basically equivalent to <img>, so IE8 treats it as such) .

Credits to David Storey’s original example that inspired this.