kunde
kunde

Reputation: 431

Gray out a section of an image with CSS

I'm trying to grey out a section of an image (two stripes at left and right). Is there a way to do this using just CSS?

I know I can use filters (i.e. filter: grayscale(100%)), but I don't want the entire image to be grey.

Upvotes: 8

Views: 6599

Answers (3)

Code Monkey
Code Monkey

Reputation: 1835

If you do indeed wish to use the greyscale filter you will need to have two images on top of each other, one with the greyscale filter applied and clipped to the size you wish.

<div class="image-container">
    <img class="image-grey clip" src="http://placekitten.com/200/150" />
    <img class="image-coloured" src="http://placekitten.com/200/150" />  
</div>

and

.image-coloured {
    z-index: 0;
    position: absolute;
}

.image-grey {
    z-index: 1;
    position: absolute;
    -webkit-filter: grayscale(100%);
}

.clip {
    clip: rect(0px,60px,150px,0px)
}

Fiddle

Upvotes: 2

Paulie_D
Paulie_D

Reputation: 115046

Pure CSS Solution with no extra markup

JSFIDDLE DEMO

HTML

<div class="image-container">
    <img class="image-grey" src="http://placekitten.com/200/150" />
</div>

CSS

.image-container {
    position:relative;
    display:inline-block;
}

.image-grey {
    display:block;
    -webkit-filter: grayscale(100%);
}

.image-container:after {
    position:absolute;
    content:"";
    top:0;
    left:50%;
        width:50%;
    height:100%;
    background-image:url(http://placekitten.com/200/150);
    background-position:top right;
}

Upvotes: 9

bjb568
bjb568

Reputation: 11498

Put a div over it.

<div id="wrapper">
    <img src="path/to/file.jpg" />
    <div id="filter">
</div>
<style>
#wrapper {position: relative;}
#filter {
    position: absolute;
    top: 123px;
    left: 123px;
    width: 42px;
    height: 42px;
    background: rgba(255,0,0,0.5);
}
</style>

http://jsfiddle.net/BQ7J3/

Upvotes: 2

Related Questions