Open In App

How to use drop-shadow on SVG element using CSS3 ?

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

SVG is used for creating images that can be scaled without losing resolution. CSS3 offers to style and animate SVG graphics. We can apply drop shadow using the ‘filter’ property. 

The ‘filter’ property allows us to apply visual effects to SVG elements. To add a drop shadow to an SVG, we can use the ‘drop-shadow()’ function. The ‘drop-shadow()’ function takes four parameters:

  • x-offset: The horizontal distance of the shadow from the element.
  • y-offset”: The vertical distance of the shadow from the element.
  • blur-radius: The amount of blurring applied to the shadow.
  • color: The color of the shadow.

Syntax:

<style>
    rect {
         filter: drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.5));
    }
</style>

 

Example 1: The below example will demonstrate the use of SVG drop shadow using CSS3:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>Drop shadow Using CSS3</title>
</head>
  
<body>
    <svg width="200" height="200">
        <rect x="20" y="20" width="100" 
            height="100" fill="#f00" />
        <text x="20" y="150" fill="green">
            GeeksforGeeks
        </text>
    </svg>
</body>
  
</html>


Output:

drop-shadow example

In the above example, we’ve applied a drop shadow to the rectangle using the ‘filter’ property and the ‘drop-shadow()’ function. The ‘x-offset‘ and ‘y-offset‘ are both set to ‘2px’, which means the shadow will be offset by 2 pixels horizontally and vertically. The ‘blur-radius’ is set to ‘4px’, which determines the amount of blur applied to the shadow. The ‘color’ is set to ‘rgba(0, 0, 0, 0.5)’, which creates a semi-transparent black shadow. You can adjust these values to create a desired shadow effect.

We can select the target element by using the CSS selector property.

Example 2: This is another example that will demonstrate the use of SVG drop shadow using css3:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Drop shadow Using CSS3</title>
    <style>
        #cr {
            filter: drop-shadow(4px 6px 1px rgb(5, 5, 5));
        }
    </style>
</head>
  
<body>
    <svg width="300" height="200">
        <circle cx="150" cy="100" 
            r="80" fill="green" id="cr" />
        <text x="150" y="125" font-size="60" 
            text-anchor="middle" fill="white">
            GFG
        </text>
    </svg>
</body>
  
</html>


Output: 

drop-shadow example

In conclusion, adding a drop shadow to an SVG using CSS3 is a powerful way to enhance the appearance of your graphics.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads