A natural shadow with SVG filters
- Published at
- Updated at
- Reading time
- 2min
I just cleaned up all the open tabs in my browser and discovered a Tweet from Jamie Kyle (if you open it, yes, I had that tab open for six months ๐). Jamie described how he implemented a natural shadow component using React and SVG filters. The shadow reflects the element's colors, and they are what give the effect its natural look.
Jamie wraps an image into an SVG element and uses SVG filter
elements to create the beautiful shadow.
That approach got me thinking, a while ago, I published a blog post describing how to inline SVG filters in CSS. It turns out you can apply Jamie's SVG filter without React or wrapping everything in an SVG element. Pure CSS does the job! ๐
Here's the CSS class with the inlined SVG filter.
.natural-shadow {
/* inline the SVG filter */
filter: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg">\
<filter id="naturalShadow" x="0" y="0" width="2" height="2">\
<feOffset in="SourceGraphic" dx="3" dy="3" />\
<feGaussianBlur stdDeviation="5" result="blur" />\
<feMerge>\
<feMergeNode in="blur"/>\
<feMergeNode in="SourceGraphic"/>\
</feMerge>\
</filter>\
</svg>#naturalShadow');
}
What's cool about this approach is that the SVG filter is visually applied to the element and its children. You can apply it to a wrapper div
such as the one below.
<div class="natural-shadow">
<img src="/your-image.png" alt="Your iamge">
</div>
See the result in action. This shadow is done in pure CSS (sort of ๐). ๐
As stated in my previous blog post, Safari seems to have some issues with inlined SVG filters. If you know what's the problem, please let me know!
Join 5.5k readers and learn something new every week with Web Weekly.