CSS filters allow you to apply various visual effects to elements on a web page without modifying the actual image data. They are often used to enhance the appearance of images, backgrounds, or even entire sections of a page. Filters can be applied to elements using the filter property.
Common CSS Filter Functions
Here are some of the most commonly used filter functions:
blur(): Creates a Gaussian blur effect, softening the edges of an element.- Example:
filter: blur(5px);
- Example:
brightness(): Adjusts the overall brightness of an element.- Example:
filter: brightness(1.2);(Increases brightness by 20%)
- Example:
contrast(): Adjusts the contrast of an element.- Example:
filter: contrast(0.8);(Decreases contrast by 20%)
- Example:
grayscale(): Converts an element to grayscale.- Example:
filter: grayscale(1);(100% grayscale)
- Example:
hue-rotate(): Rotates the hue of an element.- Example:
filter: hue-rotate(90deg);(Rotates hue by 90 degrees)
- Example:
invert(): Inverts the colors of an element.- Example:
filter: invert(1);(100% inversion)
- Example:
opacity(): Sets the opacity of an element.- Example:
filter: opacity(0.5);(50% opacity)
- Example:
saturate(): Adjusts the saturation of an element.- Example:
filter: saturate(0);(Removes all saturation)
- Example:
sepia(): Applies a sepia tone to an element.- Example:
filter: sepia(1);(100% sepia)
- Example:
Combining Filters
You can combine multiple filters on a single element by separating them with spaces:
filter: blur(5px) brightness(1.2) contrast(0.8);
Using Filters with Multiple Elements
To apply filters to multiple elements, you can use CSS selectors to target them. For example:
img {
filter: grayscale(1);
}
.button {
filter: blur(2px) brightness(1.5);
}
Additional Considerations
- Filter effects can be applied to elements with or without background images.
- Browser support for filters varies. Some older browsers may not support all filter functions.
- You can use CSS transitions to create smooth animations when applying or removing filters.