Getting Started with the Basics: A Guide to SVG Filters

Getting Started with the Basics: A Guide to SVG Filters

3 Min Read

Visual effects created by SVG s were once a mystery to me. Being more tech-oriented, I usually avoid design-related tasks like UI, layout, or typography. My expertise is in developing efficient, logical solutions, not eye-catching aesthetics.

That changed when I stumbled upon a challenge that led me to SVG filters. This exploration drew me in step by step. Fortunately, there’s some math involved, which helps me make sense of it to some degree.

Since sharing SVG filter demos, I’ve been asked by many how to begin with them. Although I believe the best way is to start experimenting with SVG filters, I’ve decided to create a starter’s guide containing the insights I wish I had when I began.

Introduction to SVG filters

All SVG filters must be within an element. If using the element solely for filters (and not graphics), it acts similarly to a element.

Set its size to 0 and hide it from screen readers.

In CSS, keep it out of the document flow, so it doesn’t impact the layout.

svg[aria-hidden='true'][height='0'] { position: fixed }

This is necessary because setting its dimensions to zero with width and height attributes might be insufficient.

In cases requiring, for example, a display: grid on the element’s parent, the takes up a grid cell by default. This isn’t ideal, but using position: fixed (or other positioning that removes it from document flow) on the solves this.

Multiple elements can be nested inside this and referenced from the CSS.

Each element must have an id attribute.

This is applied to an element that becomes the filter input:

.my-filtered-elem { filter: url(#my-filter) }

SVG filters can be chained like CSS filters:

.my-filtered-elem { filter: url(#my-1st-filter) url(#my-2nd-filter) }

They can also be combined with CSS filters:

.my-filtered-elem { filter: url(#my-1st-filter) blur(.5rem) url(#my-2nd-filter) }

All SVG filters using RGB channels should have the color-interpolation-filters attribute explicitly defined to ensure consistent results across browsers. The default varies: Safari uses sRGB, while Chrome and Firefox use linearRGB.

Conventionally, the default is linearRGB, but Safari doesn’t follow this. For proper processing, sRGB is necessary, although its full mechanics can be perplexing. This attribute is essential and should be included with the id attribute.


  

Beginners uncertain of its need should add it as a precaution. Remember, it’s best set on the filter itself, not individual elements inside it.

The element

You might also like