CSS filter property can be used to apply graphical effects to web elements, such as blur, brightness, and contrast. It can not only be applied to standard elements but also to background images. To apply filter effects to the background image of an element, there are typically several methods:
- Apply directly to the element: You can use the
filterproperty directly on the element containing the background image. This will apply the filter effect to the entire element (including text content and the background image).
css.background-filter { background-image: url('image.jpg'); filter: blur(5px); /* Apply blur effect */ }
- Use pseudo-elements: If you only want to apply
filterto the background image without affecting other content, you can use pseudo-elements. By applying the background image to::beforeor::afterpseudo-elements and usingfilteron that pseudo-element, you can ensure that only the background image is affected by the filter effect.
css.background-filter::before { content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-image: url('image.jpg'); background-size: cover; filter: blur(5px); /* Apply blur effect */ } .background-filter { position: relative; z-index: 1; }
- Apply filter to parent element: You can also apply the filter effect to the parent element of the element containing the background image. This method will affect the background image and any child elements.
css.background-filter-parent { filter: blur(5px); /* Apply blur effect */ } .background-filter-child { background-image: url('image.jpg'); }
In these examples, we used the blur() function as the value for filter, which applies a blur effect to the selected element. CSS filter also supports other functions such as brightness(), contrast(), grayscale(), sepia(), hue-rotate(), invert(), opacity(), and saturate(), which can be combined as needed to achieve different visual effects.