David Walsh Blog

CSS Filters

CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let’s have a look at how CSS filters work and how you can quickly create elements that are beautifully filtered!

There are many CSS filters to choose from: grayscale, blur, sepia, saturate, opacity, brightness, contrast, hue-rotate, and invert. While each property value generally falls between 0 and 1, there are a few exceptions. The blur property uses a unit of pixels and can be any whole number, and the hue-rotate filter value is a whole number with a “deg” unit.

The following CSS snippet will blur an element:


.myElement {
	filter: blur(2px);
}

Multiple filters are separated by spaces, so we could also add grayscale and opacity values to the blur:


.myElement {
	filter: blur(2px) grayscale(.5) opacity(0.8);
}

Let’s get crazy with hue-rotate as well:


.myElement {
	filter: blur(2px) grayscale(.5) opacity(0.8) hue-rotate(120deg);
}

If static filtering isn’t enough for you, CSS filters also animate with @-webkit-keyframes:


@keyframes testAnim {
	0% {
		filter: grayscale(0.5) blur(1px) saturate(2);
	}
	100% {
		filter: grayscale(0.2) blur(6px) saturate(9);
	}
}

/* the photo to be animated via filters */
#animatePhoto {}
#animatePhoto:hover {
	 animation-name: testAnim;
	 animation-duration: 2s;
	 animation-iteration-count: 1;
	 animation-direction: alternate;
	 animation-timing-function: ease-out;
	 animation-fill-mode: forwards;
	 animation-delay: 0s;
}

Expect a performance hit with heavy CSS filter usage; be sure to heavily test your site wherever filtering is used. CSS filters have not yet hit mobile, but assume that CSS filters will be taxing in that environment as well.

Note: I’ve yet to successfully filter a <video> tag; it’s possible that feature isn’t in the first implementation.

The additional of CSS filters to the web provides a new level of customization for images, video, and DOM nodes in general. We should see some solid, practical uses for CSS filters emerge in the coming years. Have fun playing around with CSS filters and let me know if you can think of some immediate, practical uses!