Search code examples
htmlcssopacity

Add circular fading opacity (vignette effect) to images in CSS


I want to give circular opacity to an image using CSS.

I know I can achieve opacity on images like this:

.circle img {
    opacity: 0.4;
    filter: alpha(opacity=40);
}

I know I can achieve circular images like this:

.circle {
    border-radius: 50%;
    display: inline-block;
}
.circle img {
    border-radius: 50%;
    display: block;
}

I want somehow to merge the two things above and apply the opacity only for the edges of the image, so the center of the image gets almost nothing from the opacity tag. I have searched for hours but found nothing.

Without opacity: http://jsfiddle.net/8w6szf84/47

With opacity: http://jsfiddle.net/8w6szf84/48/ -> bad opacity, want only the edges to fade...

Do I need to use Javascript on this? Any suggestions?


Solution

  • Ok, so what we can do is create a :after element that will be equal to the size of the parent. Using this we can set a background gradient that will make it appear as the image is fading into the solid colour background.

    Note: In this example I have made the gradient element a little bigger and moved it over 1px to stop a border from appearing around it. From here you can mess around to get the perfect effect that you want.

    .circle {
        border-radius: 50%;
        display: inline-block;
        position: relative;
    }
    .circle img {
        border-radius: 50%;
        display: block;
        border:1px solid #fff;
    }
    .circle:after {
        content: "";
        display: block;
        width: 100%;
        height: 100%;
        background: radial-gradient(ellipse at center, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 70%,rgba(255,255,255,1) 100%);
        border-radius: 50%;
        position: absolute;
        top: 0; left: 0;
    }
    <div class="circle">
        <img src="http://placekitten.com/200/200?image=2" />
    </div>


    Edit: Here is another version without setting a height or width and getting rid of the border that gets caused if using 100% of parent. As Vucko pointed out we don't need the negative values for the position but can use a border around the img instead.

    JsFiddle Here