htmlcsssvgsvg-filters

SVG drop shadow using css3


Is it possible to set drop shadow for an svg element using css3, something like

box-shadow: -5px -5px 5px #888;
-webkit-box-shadow: -5px -5px 5px #888;

I saw some remarks on creating shadow using filter effects. Is there an example of using CSS alone. Below is a working code where the cursor style is correctly applied, but no shadow effect. How can I get the shadow effect with the least bit of code?

svg .shadow { 
  cursor:crosshair; 
  -moz-box-shadow: -5px -5px 5px #888;
  -webkit-box-shadow: -5px -5px 5px #888;
  box-shadow: -5px -5px 5px #888; 
}   
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full"  viewBox="0 0 120 70">  
    <rect class="shadow" x="10" y="10" width="100" height="50" fill="#c66" />
</svg>


Solution

  • Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope attribute controls how much opacity to give to the dropshadow.

    Relevant bits from the example:

    <filter id="dropshadow" height="130%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
      <feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
      <feComponentTransfer>
        <feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
      </feComponentTransfer>
      <feMerge> 
        <feMergeNode/> <!-- this contains the offset blurred image -->
        <feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
      </feMerge>
    </filter>
    <circle r="10" style="filter:url(#dropshadow)"/>
    

    Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.