Search code examples
htmlcss

CSS blur and retain sharp edges using absolute div


This works just fine if img is not set to absolute:

div img {
    filter: blur(5px);
        -webkit-filter: blur(5px);
        -moz-filter: blur(5px);
        -o-filter: blur(5px);
        -ms-filter: blur(5px);
    margin: -5px -10px -10px -5px;
}
div {
    margin: 20px;
    overflow: hidden;
}

Example working fine: http://jsfiddle.net/ThinkingStiff/b8fLU/ (taken from another question)

But what if I want to do this with an absolute div using background-image?

<div id="background"></div>

#background {
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    height: 100%;
    width: 100%;
    filter: blur(5px) brightness(0.75);
    -webkit-filter: blur(5px) brightness(0.75);
    -moz-filter: blur(5px) brightness(0.75);
    -ms-filter: blur(5px) brightness(0.75);
    -o-filter: blur(5px) brightness(0.75);
    position: absolute;
    background-image: url('images/bg.png');
    z-index: 1;
}

How can I achieve the same effect (blur but with sharp edges) using the setup above?


Solution

  • put your blur element in a container like this:

    <div class="container">
        <div id="background"></div>
    </div>
    

    then instead of using height:100% and width:100% use like this:

    .container{
        position:relative;
        width:300px;          /* this is an example */
        height:300px;         /* this is an example */
        overflow:hidden;
    }
    
    #background {
        left:-15px;
        right:-15px;
        top:-15px;
        bottom:-15px;
        /* other styles */
    }
    

    you need to remove 15px (or more/less) from each side of your element.

    DEMO - Full DEMO