A recent project I was working on called for adding a drop shadow to an SVG icon. My first thought was to use the box-shadow style like I usually do for drop shadows. Unfortunately, this just added a drop shadow to the box object and not the paths in the SVG.
For this scenario, I was using an SVG sprite like the following:
<svg width="0" height="0" style="position:absolute">
<symbol id="icon-close" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve">
<polygon points="100,12.2 87.8,0 50,37.8 12.2,0 0,12.2 37.8,50 0,87.8 12.2,100 50,62.2 87.8,100 100,87.8 62.2,50 "/>
</symbol>
</svg>
After some Googling, I found a solution that worked for me. It involved adding an SVG filter to my sprite that I could apply using CSS. Below is the code I ended up adding to my sprite:
<filter id="drop-shadow">
<feGaussianBlur in="SourceAlpha" stdDeviation="2"/>
<feOffset dx="2" dy="2" result="offsetblur"/>
<feFlood flood-color="rgb(0,0,0)" flood-opacity="0.05"/>
<feComposite in2="offsetblur" operator="in"/>
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
I’m not going to go into details of what everything in the filter means, but the important parts are the feOffset
and feFlood
. Those settings will allow you to change the distance and color of your drop shadow. Here is what my final SVG sprite looked like:
<svg width="0" height="0" style="position:absolute">
<filter id="drop-shadow">
<feGaussianBlur in="SourceAlpha" stdDeviation="2"/>
<feOffset dx="2" dy="2" result="offsetblur"/>
<feFlood flood-color="rgb(0,0,0)" flood-opacity="0.05"/>
<feComposite in2="offsetblur" operator="in"/>
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
<symbol id="icon-close" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve">
<polygon points="100,12.2 87.8,0 50,37.8 12.2,0 0,12.2 37.8,50 0,87.8 12.2,100 50,62.2 87.8,100 100,87.8 62.2,50 "/>
</symbol>
</svg>
Now we can use CSS to apply our drop shadow. For this, we will be using the filter property. Here is an example of the HTML and CSS used to display the SVG.
<style>
.icon {
display: inline-block;
width: 1em;
height: 1em;
fill: currentColor;
filter: url(#drop-shadow);
}
</style>
<svg class="icon"><use xlink:href="#icon-close" /></svg>
You might be wonder what the extra CSS properties are for. These extra properties just make sure that the SVG icon takes on the font size and color of wherever it is inserted.
Now you know the proper way to add a drop shadow to an SVG.