How to Use CSS Filter: Syntax, Examples, and Tips
Use the
filter property in CSS to apply visual effects like blur, brightness, or grayscale to elements. You write it as filter: effect(value); where effect is the filter type and value controls the effect strength.Syntax
The filter property applies graphical effects to elements. You can use one or more filter functions separated by spaces.
blur(radius): Blurs the element by the given radius.brightness(%): Adjusts brightness; 100% is normal.contrast(%): Changes contrast; 100% is normal.grayscale(%): Converts to grayscale; 100% is fully gray.sepia(%): Applies a sepia tone; 100% is full sepia.invert(%): Inverts colors; 100% is full inversion.saturate(%): Saturates colors; 100% is normal.opacity(%): Changes transparency; 100% is fully opaque.
Example syntax:
css
selector {
filter: blur(5px) brightness(120%) grayscale(50%);
}Example
This example shows an image with a blur and grayscale filter applied. The image looks soft and partially gray.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS Filter Example</title> <style> img { width: 300px; filter: blur(3px) grayscale(60%); display: block; margin: 20px auto; } </style> </head> <body> <img src="https://via.placeholder.com/300" alt="Sample Image"> </body> </html>
Output
A 300px wide image displayed in the center with a soft blur and gray tone effect.
Common Pitfalls
Common mistakes when using filter include:
- Using incorrect units (e.g., forgetting
pxforblurradius). - Applying filters to elements without visible content (like empty divs).
- Expecting filters to affect child elements separately (filters apply to the whole element).
- Not considering performance impact on large or many elements.
Example of wrong and right usage:
css
/* Wrong: missing unit for blur */ div { filter: blur(5); /* Incorrect, needs 'px' */ } /* Right: correct unit */ div { filter: blur(5px); }
Quick Reference
| Filter Function | Description | Example Value |
|---|---|---|
| blur() | Blurs the element | blur(4px) |
| brightness() | Adjusts brightness | brightness(150%) |
| contrast() | Changes contrast | contrast(80%) |
| grayscale() | Converts to grayscale | grayscale(100%) |
| sepia() | Applies sepia tone | sepia(60%) |
| invert() | Inverts colors | invert(100%) |
| saturate() | Saturates colors | saturate(200%) |
| opacity() | Changes transparency | opacity(50%) |
Key Takeaways
Use the CSS
filter property to add visual effects like blur or grayscale to elements.Always include correct units like
px for blur and percentages for other filters.Multiple filters can be combined by separating them with spaces in the
filter property.Filters affect the entire element including its content and background.
Be mindful of performance when applying filters to many or large elements.