My goal is to achieve a unique CSS effect where:
An image with a color background is grayscaled and has a gradient overlay; and
Upon hover, the gradient fades out while the color fades in.
I've experimented with two techniques but haven't found a perfect solution yet. One option is to have separate grayscale and color versions of the image to minimize loading times, but I'm exploring CSS-only methods first. Any suggestions would be greatly appreciated!
Thanks!
Technique 1: Gradient plus Background-Blend-Mode
In this approach, I applied the gradient directly to the image's background and achieved the grayscale effect using a white background and the background-blend-mode property.
The main issue here is that the transition doesn't seem to work smoothly - the image jumps between states rather than transitioning gradually.
https://jsfiddle.net/Lparts4j/1/
HTML:
<div class="test"></div>
CSS:
.test {
width: 400px;
height: 400px;
background: linear-gradient(135deg, rgb(0, 47, 75) 0%, rgb(220, 66, 37) 80%), url("http://i.imgur.com/ulb7EVg.jpg");
background-color: white;
background-blend-mode: multiply, luminosity;
background-size: cover;
-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
-o-transition: all .5s ease-in-out;
transition: all .5s ease-in-out; }
.test:hover {
background: url("http://i.imgur.com/ulb7EVg.jpg");
background-color: white;
background-blend-mode: normal;
background-size: cover; }
Technique 2: Grayscale Filter plus Gradient in :Before Element
In this method, I used a :before element for the gradient and applied the grayscale effect with the filter property.
The fade effect works well in this scenario. However, I struggled with combining the gradient and grayscale without losing color in the gradient.
https://jsfiddle.net/548afgjf/4/
HTML:
<div class="img img-one"></div>
<div class="img img-two"></div>
CSS:
.img {
position: relative;
display: inline-block;
width: 300px;
height: 400px; }
.img-one {
background: url('http://i.imgur.com/ulb7EVg.jpg') center center / cover no-repeat;
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
-o-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
.img-one:before {
content:'';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: .6;
background: rgb(0, 47, 75);
/* Remaining CSS properties omitted for brevity */
}
.img-one:hover {
-webkit-filter: grayscale(0%);
filter: grayscale(0%);
}
.img-one:hover:before {
opacity: 0; }
.img-two {
background: url('http://i.imgur.com/ulb7EVg.jpg') center center / cover no-repeat;
/* Remaining CSS properties omitted for brevity */
}
.img-two:before {
content:'';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: .6;
background: rgb(0, 47, 75);
/* Remaining CSS properties omitted for brevity */
}
.img-two:hover:before {
opacity: 0; }