filters

The Contrast Swap Technique: Improved Image Performance with CSS Filters

With CSS filter effects and blend modes, we can now leverage various techniques for styling images directly in the browser. However, creating aesthetic theming isn't all that filter effects are good for. You can use filters to indicate hover state, hide passwords, and now—for web performance.

While playing with profiling performance wins of using blend modes for duotone image effects (I'll write up an article on this soon), I discovered something even more exciting. A major image optimization win! The idea is to reduce image contrast in the source image, reducing its file size, then boosting the contrast back up with CSS filters!

(more…)

Breaking down CSS Box Shadow vs. Drop Shadow

Drop shadows. Web designers have loved them for a long time to the extent that we used to fake them with PNG images before CSS Level 3 formally introduced them to the spec as the box-shadow property. I still reach for drop shadows often in my work because they add a nice texture in some contexts, like working with largely flat designs.

Not too long after box-shadow was introduced, a working draft for CSS Filters surfaced and, with it, a method for drop-shadow() that looks a lot like box-shadow at first glance. However, the two are different and it's worth comparing those differences.

(more…)

Using Filters in Vue.js

Filters are an interesting way to deal with data rendering in Vue but are only useful in a small amount of cases. The first thing to understand about filters is that they aren't replacements for methods, computed values, or watchers, because filters don't transform the data, just the output that the user sees. As of Vue 2.0, there are no built-in filters, we need to construct them ourselves.

(more…)

Frosting Glass with CSS Filters

While filters such as contrast, saturate, and blur have existed in image editors for some time, delivering them on the web has historically required serving images with those filters already applied. As browsers begin to incorporate filters as part of the web platform, we can begin breaking down complex visual effects into their component parts, and implementing them on the web. This article will examine one such effect, frosted glass, and how CSS filters provide a cleaner, more flexible solution than static images.

Old School: Frosted Glass with Images

The frosted glass effect has been kicking around the internet for a while; we even saw it here on CSS-Tricks back in 2008. The idea behind the effect is relatively simple: just blur and lighten the area behind overlaid content. The content gains higher contrast with its background, but you still maintain a rough idea of what's going on behind it. The CSS-Tricks article uses two images: a standard version and a frosted version (blurred with a white tint). In our example, a card slides up to reveal content, while frosting over the background.

Demo

See the Pen Frosted Glass Effect Using Multiple Images by betravis (@betravis) on CodePen.

The HTML

The markup is relatively simple. We only have a single article that contains content.

<article class="glass down">
  <h1>Pelican</h1>
  <p>additional content...</p>
</article>

The CSS

We first size everything to the viewport. Then, we overlay a blurred version of the background on top of the original background. Finally, we add a white tint. The overflow is hidden to prevent scrolling and to clip the effect to the .glass element.

html, body, .glass {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
body {
    background-image: url('pelican.jpg');
    background-size: cover;
}
.glass::before {
    display: block;
    width: 100%;
    height: 100%;
    background-image: url('pelican-blurry.jpg');
    background-size: cover;
    content: ' ';
    opacity: 0.4;
}
.glass {
    background-color: white;
}

The above CSS will create our blurred and lightened overlay. We also need to shift the overlay down to the bottom of the page, leaving just enough space to view the header text. Since the blurred image is a child of the overlay, we also need to shift it back up by the opposite amount in order to keep it aligned with the body background. Because the demo uses transitions, I chose to use CSS transforms rather than the background-attachment property, as CSS transforms can be hardware accelerated.

.glass.down {
    transform: translateY(100%) translateY(-7rem);
}
.glass.down::before {
    transform: translateY(-100%) translateY(7rem);
}
.glass.up, .glass.up::before {
    transform: translateY(0);
}

Notes

The above technique is straightforward, and has solid browser support. Although I spruced up the demo a bit with transitions, the other required features – generated content, opacity, transforms and background-size – all have solid browser support ranging back to IE 9 (with the exception of Opera Mini).

New School: Frosted Glass with Filters

The duplicate image technique requires maintaining a blurred image along with the original, which can become a pain if you need to reuse the effect for multiple images. For example, responsive designs may require swapping in different images at different screen sizes. Or, template layouts may drop in images dynamically (eg, a different header image for every blog post). For these cases, it would be nice to generate the effect using only the source image. After all, we're just blurring it.

This is where CSS Filters come in handy. They allow us to apply the blur in the browser, using the CSS filter property.

The CSS

We can adjust the CSS for the frosted glass overlay to be the original image with a blur filter applied.

.glass::before {
    background-image: url('pelican-blurry.jpg');
}
.glass::before {
    background-image: url('pelican.jpg');
    filter: blur(5px);
}

Demo

See the Pen Frosted Glass Effect Using Filter Effects by betravis (@betravis) on CodePen.

Caveats

Easy peasy, right? Unfortunately, CSS Filters are somewhat new. That means they may be vendor prefixed, and that their browser support is not yet universal. However, filters have a longer history in SVG, and applying SVG filters to HTML content via CSS has wider browser support. You can easily add them as a fallback for when CSS filters are not supported. The above demo actually does just that.

To add an SVG filter, we include some inline SVG in our HTML markup, and reference the filter with a url(). Pro tip: An alternative is to encode the SVG filter and reference as a data url, but that format is a bit more difficult to read in an article.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <filter id="blur">
      <feGaussianBlur stdDeviation="5" />
    </filter>
  </defs>
</svg>
.glass::before {
    background-image: url('pelican.jpg');
    /* Fallback to SVG filters */
    filter: url('#blur');
    filter: blur(5px);
}

There will still be cases where neither CSS nor SVG Filters are supported by a browser. In that case, the user will see text on a lightened (tinted but unblurred) background, which isn't too shabby.

Conclusion

Filters allow us to use effects in the browser that were previously only available in image editors. As an element's style, rather than a rendered image, they are easier to alter and reuse. You can use CSS Filters in current versions of Chrome, Safari, and Opera, and they are under active development in Firefox (no word yet on Internet Explorer). With a little care towards fallback behavior, you can start using them today.

SVG Filters on Text

The following is a guest post by Chris Scott. Chris was messing around with SVG filters and how they can be applied to text. I thought this was quite interesting because SVG filters are quite a bit different than CSS filters. Arguably more powerful, as there are more of them and you can do things like bevel/emboss or stroke which you can't in CSS filters. Chris goes into detail here on how it's done including a tool to make it even easier.

There has been a general trend in Web development, for some years now, away from using images in designs. Only a few years ago software companies would favour using an image of a rounded corner as the best "cross-browser" solution; the CSS attribute border-radius has made that technique seem very antiquated today. Titles are another example of this trend, where in the past one may have generated a fancy banner title in Photoshop and used an image to show it on the page. These days we have web fonts at our disposal and CSS3 to help us achieve shadows and other effects. These solutions load much faster, scale better and are more accessible and semantically correct. But there is even more we can do!

SVG Filters

SVG with Filter Effects have a lot of potential for complex text styling. Take a look at this example:

See the Pen SVG Filters on Text by chrismichaelscott (@chrismichaelscott) on CodePen

That line is created using SVG Filter Effects. It's just text. You can select it with your cursor. Search engines can index it. It will scale in size without losing quality. To boot, it takes very little time to download. You can achieve a whole lot more, too, the scope for creativity with Filter Effects is huge. The example was created with a library called Raphael.js and an extension I wrote for it. This article talks about the rationale for developing the extension and shows - in brief - how it can be used.

Apparently, only 0.1% of Web pages use SVG graphics. If that statistic is anything to go by, there's a good chance that you are probably not using SVG on a regular basis. Why is SVG used so unpopular? It's only a guess, but the reason I didn't get into SVG (until I absolutely had to) was its learning curve: SVG is an XML vocabulary and is, I think, extremely technical (matrix multiplication for colour shifts, anyone?). The way I got into SVG was through Raphael.js, a JavaScript Library for creating vector drawings. Because it's a JavaScript library it felt fairly familiar, all of the complexity was abstracted away. Before long I was creating complex graphics like a pro.

Filter Effects for Raphael

Raphael has a shortcoming though: no support for Filter Effects. I remember one of my customers specifically requesting a drop shadow for bubbles in a data visualization which was interactive and animated. The request stumped me for a while as I bumped into this limit of Raphael. For that project, I wrote a very specific extension to Raphael for handling drop shadows. But the same complexity that had initially put me off SVG was back and worse than ever. Make no mistake, Filter Effects are very, very technical.

So, after that project, I set about building a more full-featured library to make Filter Effects as easy to apply as Raphael makes drawing shapes.

Introducing Filter Effects for Raphael!

Here's how to use it:

First, the HTML. This bit is dead simple, just a div with an id:

<div id="title-container"></div>

Everything else is done in JavaScript.

To start an SVG drawing with Raphael you create a "paper" by referencing the id of the container element:

var paper = Raphael("title-container");

Now to do some drawing. This example creates some text and sets some of the style attributes:

// The first two arguments are the origin of the text
var title = paper.text(0, 30, "Filters are ice cold");
title.attr({
"fill": "MintCream",
"font-family": "Butcherman",
"font-size": "54px",
"text-anchor": "start"
});

Now for some effects! The simplest things you can do are shadows, blurring, lighting, embossing and colour shifting. Those require very little coding. Let's try the emboss effect. Add to the JavaScript:

title.emboss();

You can chain effects, so applying a shadow afterwards is straightforward:

title.emboss().shadow();

Pretty cool, huh? You can take this much further if you want, by creating your own filters. The SVG spec lists (lower level) filter effects which can be combined to create all kinds of filters (convulsion matrices, in particular, can be used for a vast number of operations).

This demo has the full code and some other examples of different effects that can be achieved:

See the Pen SVG Filters on Text by Chris Coyier (@chriscoyier) on CodePen.

Shortcomings

What are the downsides to SVG? Well - aside from the pros and cons of vector over raster (like canvas) - there are a couple I can think of:

  • Browser support - You may not be surprised to learn that the graphical trickery discussed here is not supported in older versions of IE, 10 only. SVG itself will render in IE9, just without the effects. Firefox, Chrome and Opera have supported Filter Effects for ages
  • Semantics - Some may have reservations about the semantic validity of using SVG in documents, certainly the svg tag doesn't give any clue as to it's content; you can use a sensible parent, though

Wrapping Up

Hopefully, this piece has given you a good idea of what filter effects can do and how Filter Effects for Raphael can do them. Check out the project page on Github for more details. Thanks for reading!

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag