How to use SVG Filters In CSS
- SVG (Scalable Vector Graphics) filters provide a more easier and flexible way to apply filter effects to images or other HTML elements.
- SVG filters are defined in an <svg> element with <filter> elements inside. These filters can be composed of various primitive filters, such as <feGaussianBlur>, <feColorMatrix>, <feComposite>, and more.
- To use SVG filters, you need to define a filter in an SVG element, and then apply it to an image using the filter attribute.
Example: The below code uses SVG filters to add a filter effect to the images.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
CSS SVG Effects Example
</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="image-container">
<img alt="GFG Image" id="gfg-image" src=
"https://media.w3wiki.org/wp-content/uploads/20210915115837/gfg3-300x300.png">
</div>
<svg width="0" height="0">
<filter id="blur" x="-50%" y="-50%"
width="200%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="5" />
</filter>
</svg>
<script>
const image =
document.getElementById('gfg-image');
image.style.filter = "url(#blur)";
</script>
</body>
</html>
.image-container {
width: 300px;
margin: 20px auto;
text-align: center;
}
img {
width: 100%;
height: auto;
border-radius: 10px;
transition: filter 0.3s ease;
}
img:hover {
filter: grayscale(100%);
}
Output:
How to Add Filter Effects to Images ?
Adding filter effects to images can make images more enhanced on your website. Filter effects can be started from simple adjustments like brightness and contrast to more complex effects like blur, color overlays, and many more.
The below approaches can be used to add filter effect to images:
Table of Content
- Using CSS Filters
- Using SVG Filters
- Using CSS Blend Modes