Filters
Traditionally, if you wanted to blur an image or change its brightness, you had to open Photoshop or a similar editor. CSS Filters change that. They allow you to perform powerful graphical operations directly in the browser.
The filter property can be applied to any HTML element, though it is most commonly used on <img> tags. You can even chain multiple filters together to create complex artistic effects.
1. Visual Clarity: blur() and opacity()
The blur() function softens the edges of an element, while opacity() controls how much you can see through it.
Pro Tip: While CSS has a standaloneopacityproperty, usingfilter: opacity()can be hardware-accelerated by the GPU, leading to smoother performance in some browsers.
Code Block Loading...
2. The Smart Shadow: drop-shadow()
The drop-shadow() filter is smarter than box-shadow. It follows the alpha channel of an image. If you have a transparent PNG of a person, the shadow will wrap around their body, not the rectangular box of the image file.
Code Block Loading...
3. Color Manipulation: grayscale(), sepia(), and invert()
These functions allow you to transform the color profile of an element.
grayscale(): Turns the image black and white.sepia(): Gives a vintage, warm brown look.invert(): Flips colors to their opposite on the HSL color wheel (e.g., Red becomes Cyan).
Code Block Loading...
4. Advanced Toning: brightness(), contrast(), and saturate()
These filters function exactly like the sliders on your phone's photo editor:
brightness(): 0% is black, 100% is original, >100% is brighter.contrast(): 0% is solid gray, 100% is original.saturate(): Controls the intensity of the colors.
Code Block Loading...
5. Creative Colors: hue-rotate()
The hue-rotate() function moves all colors of the element around the HSL color wheel by a specific degree ($0^\circ$ to $360^\circ$).
Code Block Loading...
6. Chaining Multiple Filters
You are not limited to one effect! You can combine filters by listing them with spaces.
Code Block Loading...
Key Takeaways
- Dynamic Effects: Use filters for hover states (e.g., an image that starts grayscale and turns to color when hovered).
- Alpha-Aware: Prefer
drop-shadow()overbox-shadowfor transparent PNGs or SVG icons. - Performance: Filters are generally high-performance, but heavy
blur()effects on large elements can impact scroll smoothness. - The 50% Invert Rule: Using
invert(50%)will always result in a medium gray because you are exactly in the middle of the color wheel.