Takeflight - Web design and web development

Fudging masks using CSS blend modes

One of the features I'm super excited about is masking using SVGs. But the limited support for masking or applying SVG filters to HTML elements meant having to turn any text or images into SVG instead of HTML. Which I'm not a fan of.

Then I started spending some time with blend modes and found I could achieve many of the masks I needed using them instead. The idea is fairly simple. Use a combination of the darken and lighten blend modes along with black and white shapes made using plain css to mask off sections of one html element and let layers below them become visible.

It's worth pointing out that you can achieve the same effect exhibited here with better browser support using clip-path - thanks @SaraSoueidan  for pointing this out. BUT if you want to use text as part of your mask that means putting it in an external SVG file. This method allows you to keep it in the main HTML document - where it belongs ;)

You've been warned. In lieu of this being useful, see it as an interesting hack.

An example; this (ugly) loading animation inspired by Peggles between level screen:

See the Pen Faking masks with mix-blend-modes by Jonny Scholes (@jonnyscholes) on CodePen.

Lets say we want to have a background image and then a triangle portion of another image centered ontop of it. We can do that with pure css, no SVGs and fairly decent support: Firefox, Chrome and Safari - no IE :(

It doesnt have to be a triangle - it can be any sharp edged shape made using css.

Conceptually this is what we're going to do:


First make a layer that includes the background image and a white silhouette of the triangle on top. This will be called the base.

Second make a layer that has a white background and a black silouette of the triangle in the same position. We'll refer to this layer as the 'mask'.

Thirdly within the mask layer add the image you want to be clipped into the triangle. Set the mix-blend-mode of the mask layer to darken so that when it combines with the base layer the white pixels of the mask layer will disapear (because you can't darken anything with white) leaving only the pixels within the mask triangle which will darken the pixels in the white triangle of the base layer.

Obviously this should use this only as an enhancement as IE doesnt support mix-blend-modes at all.

I find its easier to understand with code so here is a pen I set up to walk you through it.

See the Pen xGwPaL by Jonny Scholes (@jonnyscholes) on CodePen.

Orginally posted on Codepen, May 6th 2015