Home  >  Article  >  Web Front-end  >  How to Blur the Background Image of an Element in CSS While Keeping the Content Sharp?

How to Blur the Background Image of an Element in CSS While Keeping the Content Sharp?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 21:11:02924browse

How to Blur the Background Image of an Element in CSS While Keeping the Content Sharp?

Blur Background Image in CSS Without Affecting Content

In CSS, you may encounter a situation where you want to blur the background image of an element without affecting the content inside it. Here's how you can achieve this:

The solution involves creating a pseudo-element (:before) that inherits the background image of the parent element. This pseudo-element is then positioned absolutely and given a blur filter. By setting its z-index to -1, it appears behind the content.

To implement this, apply the following CSS:

<code class="css">.blur-bgimage {
    overflow: hidden;
    margin: 0;
    text-align: left;
}

.blur-bgimage:before {
    content: "";
    position: absolute;
    width : 100%;
    height: 100%;
    background: inherit;
    z-index: -1;

    filter        : blur(10px);
    -moz-filter   : blur(10px);
    -webkit-filter: blur(10px);
    -o-filter     : blur(10px);

    transition        : all 2s linear;
    -moz-transition   : all 2s linear;
    -webkit-transition: all 2s linear;
    -o-transition     : all 2s linear;
}</code>

You can then use JavaScript to toggle a class (e.g., 'blur-bgimage') that applies this CSS to the desired element, blurring or unblurring the background image as needed.

The above is the detailed content of How to Blur the Background Image of an Element in CSS While Keeping the Content Sharp?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn